本文将分享将多个WebSecurityConfigurerAdapter与不同的AuthenticationProviders一起使用的详细内容,并且还将对API的基本身份验证和Web应用程序的LDA
本文将分享将多个WebSecurityConfigurerAdapter与不同的AuthenticationProviders一起使用的详细内容,并且还将对API的基本身份验证和Web应用程序的LDAP进行详尽解释,此外,我们还将为大家带来关于org.apache.hadoop.security.authentication.util.SignerSecretProvider的实例源码、org.apache.hadoop.security.authentication.util.ZKSignerSecretProvider的实例源码、org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration.WebMvcAutoConfigurationAdapter的实例源码、org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter的实例源码的相关知识,希望对你有所帮助。
本文目录一览:- 将多个WebSecurityConfigurerAdapter与不同的AuthenticationProviders一起使用(API的基本身份验证和Web应用程序的LDAP)
- org.apache.hadoop.security.authentication.util.SignerSecretProvider的实例源码
- org.apache.hadoop.security.authentication.util.ZKSignerSecretProvider的实例源码
- org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration.WebMvcAutoConfigurationAdapter的实例源码
- org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter的实例源码
将多个WebSecurityConfigurerAdapter与不同的AuthenticationProviders一起使用(API的基本身份验证和Web应用程序的LDAP)
我尝试做同样的事情,但没有成功。重新启动服务器后,API的前x次可以在基本身份验证下正常运行,但是几次后,我被重定向到登录(表单)页面,这仅应在我们的Web应用程序上发生,而不是在API调用上发生。
我的代码:
@EnableWebSecuritypublic class MultiHttpSecurityConfig { @Configuration @Order(1) public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter { @Autowired private Environment env; @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication(). withUser("admin").password("pw_test").roles(API_ROLE); } protected void configure(HttpSecurity http) throws Exception { http .antMatcher("/services/**") .authorizeRequests() .anyRequest().hasRole(API_ROLE) .and() .httpBasic() .and() .csrf() .disable(); } } @Configuration @Order(2) public static class FormLoginWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter { @Autowired private Environment env; @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.authenticationProvider(activeDirectoryLdapAuthenticationProvider()); auth.eraseCredentials(false); } @Override protected void configure(HttpSecurity http) throws Exception { // LDAP FORM AUTHENTICATION http.authorizeRequests() .antMatchers("/login.html").permitAll() .antMatchers("/css/**").permitAll() .antMatchers("/js/**").permitAll() .antMatchers("/images/**").permitAll() .anyRequest().authenticated() .and().formLogin() .failureUrl("/login.html?error=1") .loginPage("/login.html") .loginProcessingUrl("/j_spring_security_check") .defaultSuccessUrl("/success.html") .usernameParameter("j_username") .passwordParameter("j_password") .permitAll(); http.csrf().disable(); // iFRAMES SETTINGS http .headers() .frameOptions().sameOrigin() .httpStrictTransportSecurity().disable(); // HTTPS http .requiresChannel() .anyRequest() .requiresSecure(); //MAP 8080 to HTTPS PORT http.portMapper().http(8080).mapsTo(443); } @Bean public AuthenticationProvider activeDirectoryLdapAuthenticationProvider() { CustomLdapAuthenticationProvider provider = new CustomLdapAuthenticationProvider(env.getProperty("ldap.domain"), env.getProperty("ldap.url"), env.getProperty("ldap.base")); provider.setConvertSubErrorCodesToExceptions(true); provider.setUseAuthenticationRequestCredentials(true); return provider; } }}
任何的想法?
我正在使用Spring Boot版本1.4.1-RELEASE和Spring Security版本4.1.3-RELEASE。
答案1
小编典典AuthenticationManager
两种配置都使用相同的配置,因为你可以自动连接AuthenticationManagerBuilder
。
请参阅Spring Security Architecture:
@Configurationpublic class ApplicationSecurity extends WebSecurityConfigurerAdapter { ... // web stuff here @Autowired public initialize(AuthenticationManagerBuilder builder, DataSource dataSource) { auth.jdbcAuthentication().dataSource(dataSource).withUser("dave") .password("secret").roles("USER"); }}
此示例与Web应用程序有关,但是的用法AuthenticationManagerBuilder
更为广泛(有关如何实现Web应用程序安全性的详细信息,请参见下文)。请注意,AuthenticationManagerBuilder
是@Autowired
进入的一个方法@Bean
-这是什么使得它建立全局(父)的AuthenticationManager
。相反,如果我们这样做的话:
@Configurationpublic class ApplicationSecurity extends WebSecurityConfigurerAdapter { @Autowired DataSource dataSource; ... // web stuff here @Override public configure(AuthenticationManagerBuilder builder) { auth.jdbcAuthentication().dataSource(dataSource).withUser("dave") .password("secret").roles("USER"); }}
(@Override
在配置程序中使用an 方法),AuthenticationManagerBuilder
则仅用于构建“本地” AuthenticationManager
,它是全局变量的子级。
org.apache.hadoop.security.authentication.util.SignerSecretProvider的实例源码
private static SignerSecretProvider getMockedServletContextWithStringSigner( FilterConfig config) throws Exception { Properties secretProviderProps = new Properties(); secretProviderProps.setProperty(AuthenticationFilter.SIGNATURE_SECRET,"secret"); SignerSecretProvider secretProvider = StringSignerSecretProviderCreator.newStringSignerSecretProvider(); secretProvider.init(secretProviderProps,null,TOKEN_VALIDITY_SEC); ServletContext context = Mockito.mock(ServletContext.class); Mockito.when(context.getAttribute( AuthenticationFilter.SIGNER_SECRET_PROVIDER_ATTRIBUTE)) .thenReturn(secretProvider); Mockito.when(config.getServletContext()).thenReturn(context); return secretProvider; }
private static SignerSecretProvider getMockedServletContextWithStringSigner( FilterConfig config) throws Exception { Properties secretProviderProps = new Properties(); secretProviderProps.setProperty(AuthenticationFilter.SIGNATURE_SECRET,TOKEN_VALIDITY_SEC); ServletContext context = Mockito.mock(ServletContext.class); Mockito.when(context.getAttribute( AuthenticationFilter.SIGNER_SECRET_PROVIDER_ATTRIBUTE)) .thenReturn(secretProvider); Mockito.when(config.getServletContext()).thenReturn(context); return secretProvider; }
private static SignerSecretProvider getMockedServletContextWithStringSigner( FilterConfig config) throws Exception { Properties secretProviderProps = new Properties(); secretProviderProps.setProperty(AuthenticationFilter.SIGNATURE_SECRET,TOKEN_VALIDITY_SEC); ServletContext context = Mockito.mock(ServletContext.class); Mockito.when(context.getAttribute( AuthenticationFilter.SIGNER_SECRET_PROVIDER_ATTRIBUTE)) .thenReturn(secretProvider); Mockito.when(config.getServletContext()).thenReturn(context); return secretProvider; }
@Override public void initializeSecretProvider(FilterConfig filterConfig) throws servletexception { LOG.debug("AtlasAuthenticationFilter :: initializeSecretProvider {}",filterConfig); secretProvider = (SignerSecretProvider) filterConfig.getServletContext(). getAttribute(AuthenticationFilter.SIGNER_SECRET_PROVIDER_ATTRIBUTE); if (secretProvider == null) { // As tomcat cannot specify the provider object in the configuration. // It'll go into this path String configPrefix = filterConfig.getinitParameter(CONfig_PREFIX); configPrefix = (configPrefix != null) ? configPrefix + "." : ""; try { secretProvider = AuthenticationFilter.constructSecretProvider( filterConfig.getServletContext(),super.getConfiguration(configPrefix,filterConfig),false); this.isInitializedByTomcat = true; } catch (Exception ex) { throw new servletexception(ex); } } signer = new Signer(secretProvider); }
private static SignerSecretProvider getMockedServletContextWithStringSigner( FilterConfig config) throws Exception { Properties secretProviderProps = new Properties(); secretProviderProps.setProperty(AuthenticationFilter.SIGNATURE_SECRET,TOKEN_VALIDITY_SEC); ServletContext context = Mockito.mock(ServletContext.class); Mockito.when(context.getAttribute( AuthenticationFilter.SIGNER_SECRET_PROVIDER_ATTRIBUTE)) .thenReturn(secretProvider); Mockito.when(config.getServletContext()).thenReturn(context); return secretProvider; }
private static SignerSecretProvider constructSecretProvider(final Builder b,ServletContext ctx) throws Exception { final Configuration conf = b.conf; Properties config = getFilterProperties(conf,b.authFilterConfigurationPrefix); return AuthenticationFilter.constructSecretProvider( ctx,config,b.disallowFallbackToRandomSignerSecretProvider); }
private static SignerSecretProvider constructSecretProvider(final Builder b,b.disallowFallbackToRandomSignerSecretProvider); }
@Test public void testGetToken() throws Exception { AuthenticationFilter filter = new AuthenticationFilter(); try { FilterConfig config = Mockito.mock(FilterConfig.class); Mockito.when(config.getinitParameter("management.operation.return")). thenReturn("true"); Mockito.when(config.getinitParameter(AuthenticationFilter.AUTH_TYPE)).thenReturn( DummyAuthenticationHandler.class.getName()); Mockito.when(config.getinitParameter(AuthenticationFilter.SIGNATURE_SECRET)).thenReturn("secret"); Mockito.when(config.getinitParameterNames()).thenReturn( new Vector<String>( Arrays.asList(AuthenticationFilter.AUTH_TYPE,AuthenticationFilter.SIGNATURE_SECRET,"management.operation.return")).elements()); SignerSecretProvider secretProvider = getMockedServletContextWithStringSigner(config); filter.init(config); AuthenticationToken token = new AuthenticationToken("u","p",DummyAuthenticationHandler.TYPE); token.setExpires(System.currentTimeMillis() + TOKEN_VALIDITY_SEC); Signer signer = new Signer(secretProvider); String tokenSigned = signer.sign(token.toString()); Cookie cookie = new Cookie(AuthenticatedURL.AUTH_COOKIE,tokenSigned); HttpServletRequest request = Mockito.mock(HttpServletRequest.class); Mockito.when(request.getCookies()).thenReturn(new Cookie[]{cookie}); AuthenticationToken newToken = filter.getToken(request); Assert.assertEquals(token.toString(),newToken.toString()); } finally { filter.destroy(); } }
private static SignerSecretProvider constructSecretProvider(final Builder b,b.disallowFallbackToRandomSignerSecretProvider); }
@Test public void testGetToken() throws Exception { AuthenticationFilter filter = new AuthenticationFilter(); try { FilterConfig config = Mockito.mock(FilterConfig.class); Mockito.when(config.getinitParameter("management.operation.return")). thenReturn("true"); Mockito.when(config.getinitParameter(AuthenticationFilter.AUTH_TYPE)).thenReturn( DummyAuthenticationHandler.class.getName()); Mockito.when(config.getinitParameter(AuthenticationFilter.SIGNATURE_SECRET)).thenReturn("secret"); Mockito.when(config.getinitParameterNames()).thenReturn( new Vector<String>( Arrays.asList(AuthenticationFilter.AUTH_TYPE,newToken.toString()); } finally { filter.destroy(); } }
private static void verifyAuthorized(AuthenticationFilter filter,HttpServletRequest request,HttpServletResponse response,FilterChain chain) throws Exception { final Map<String,String> cookieMap = new HashMap<>(); Mockito.doAnswer(new Answer<Object>() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { String cookieHeader = (String) invocation.getArguments()[1]; parseCookieMap(cookieHeader,cookieMap); return null; } }).when(response).addHeader(Mockito.eq("Set-Cookie"),Mockito.anyString()); filter.doFilter(request,response,chain); String v = cookieMap.get(AuthenticatedURL.AUTH_COOKIE); Assert.assertNotNull("cookie missing",v); Assert.assertTrue(v.contains("u=") && v.contains("p=") && v.contains ("t=") && v.contains("i=") && v.contains("e=") && v.contains("s=")); Mockito.verify(chain).doFilter(Mockito.any(ServletRequest.class),Mockito.any(ServletResponse.class)); SignerSecretProvider secretProvider = StringSignerSecretProviderCreator.newStringSignerSecretProvider(); Properties secretProviderProps = new Properties(); secretProviderProps.setProperty( AuthenticationFilter.SIGNATURE_SECRET,"secret"); secretProvider.init(secretProviderProps,TOKEN_VALIDITY_SEC); Signer signer = new Signer(secretProvider); String value = signer.verifyAndExtract(v); AuthenticationToken token = AuthenticationToken.parse(value); assertthat(token.getMaxInactives(),not(0L)); assertthat(token.getExpires(),not(0L)); Assert.assertFalse("Token is expired.",token.isExpired()); }
private static SignerSecretProvider constructSecretProvider(final Builder b,b.disallowFallbackToRandomSignerSecretProvider); }
@Test public void testGetToken() throws Exception { AuthenticationFilter filter = new AuthenticationFilter(); try { FilterConfig config = Mockito.mock(FilterConfig.class); Mockito.when(config.getinitParameter("management.operation.return")). thenReturn("true"); Mockito.when(config.getinitParameter(AuthenticationFilter.AUTH_TYPE)).thenReturn( DummyAuthenticationHandler.class.getName()); Mockito.when(config.getinitParameter(AuthenticationFilter.SIGNATURE_SECRET)).thenReturn("secret"); Mockito.when(config.getinitParameterNames()).thenReturn( new Vector<String>( Arrays.asList(AuthenticationFilter.AUTH_TYPE,newToken.toString()); } finally { filter.destroy(); } }
@SuppressWarnings("unchecked") private Class<? extends SignerSecretProvider> getProviderClass(Properties config) throws servletexception { String providerClassName; String signerSecretProviderName = config.getProperty(SIGNER_SECRET_PROVIDER,null); // fallback to old behavior if (signerSecretProviderName == null) { String signatureSecret = config.getProperty(SIGNATURE_SECRET,null); if (signatureSecret != null) { providerClassName = StringSignerSecretProvider.class.getName(); } else { providerClassName = RandomSignerSecretProvider.class.getName(); randomSecret = true; } } else { if ("random".equals(signerSecretProviderName)) { providerClassName = RandomSignerSecretProvider.class.getName(); randomSecret = true; } else if ("string".equals(signerSecretProviderName)) { providerClassName = StringSignerSecretProvider.class.getName(); } else if ("zookeeper".equals(signerSecretProviderName)) { providerClassName = ZKSignerSecretProvider.class.getName(); } else { providerClassName = signerSecretProviderName; customSecretProvider = true; } } try { return (Class<? extends SignerSecretProvider>) Thread.currentThread(). getContextClassLoader().loadClass(providerClassName); } catch (ClassNotFoundException ex) { throw new servletexception(ex); } }
private static SignerSecretProvider constructSecretProvider(final Builder b,b.disallowFallbackToRandomSignerSecretProvider); }
private Signer getSignerToEncrypt() throws Exception { SignerSecretProvider secretProvider = StringSignerSecretProviderCreator.newStringSignerSecretProvider(); Properties secretProviderProps = new Properties(); secretProviderProps.setProperty( AuthenticationFilter.SIGNATURE_SECRET,SECRET_STR); secretProvider.init(secretProviderProps,TIMEOUT); return new Signer(secretProvider); }
@Test public void testGetToken() throws Exception { AuthenticationFilter filter = new AuthenticationFilter(); try { FilterConfig config = Mockito.mock(FilterConfig.class); Mockito.when(config.getinitParameter("management.operation.return")). thenReturn("true"); Mockito.when(config.getinitParameter(AuthenticationFilter.AUTH_TYPE)).thenReturn( DummyAuthenticationHandler.class.getName()); Mockito.when(config.getinitParameter(AuthenticationFilter.SIGNATURE_SECRET)).thenReturn("secret"); Mockito.when(config.getinitParameterNames()).thenReturn( new Vector<String>( Arrays.asList(AuthenticationFilter.AUTH_TYPE,newToken.toString()); } finally { filter.destroy(); } }
@Test public void testGetTokenExpired() throws Exception { AuthenticationFilter filter = new AuthenticationFilter(); try { FilterConfig config = Mockito.mock(FilterConfig.class); Mockito.when(config.getinitParameter("management.operation.return")).thenReturn("true"); Mockito.when(config.getinitParameter(AuthenticationFilter.AUTH_TYPE)).thenReturn( DummyAuthenticationHandler.class.getName()); Mockito.when(config.getinitParameter(AuthenticationFilter.SIGNATURE_SECRET)).thenReturn("secret"); Mockito.when(config.getinitParameterNames()).thenReturn( new Vector<String>( Arrays.asList(AuthenticationFilter.AUTH_TYPE,"management.operation.return")).elements()); getMockedServletContextWithStringSigner(config); filter.init(config); AuthenticationToken token = new AuthenticationToken("u",DummyAuthenticationHandler.TYPE); token.setExpires(System.currentTimeMillis() - TOKEN_VALIDITY_SEC); SignerSecretProvider secretProvider = StringSignerSecretProviderCreator.newStringSignerSecretProvider(); Properties secretProviderProps = new Properties(); secretProviderProps.setProperty( AuthenticationFilter.SIGNATURE_SECRET,"secret"); secretProvider.init(secretProviderProps,TOKEN_VALIDITY_SEC); Signer signer = new Signer(secretProvider); String tokenSigned = signer.sign(token.toString()); Cookie cookie = new Cookie(AuthenticatedURL.AUTH_COOKIE,tokenSigned); HttpServletRequest request = Mockito.mock(HttpServletRequest.class); Mockito.when(request.getCookies()).thenReturn(new Cookie[]{cookie}); boolean Failed = false; try { filter.getToken(request); } catch (AuthenticationException ex) { Assert.assertEquals("AuthenticationToken expired",ex.getMessage()); Failed = true; } finally { Assert.assertTrue("token not expired",Failed); } } finally { filter.destroy(); } }
@Test public void testGetTokenInvalidType() throws Exception { AuthenticationFilter filter = new AuthenticationFilter(); try { FilterConfig config = Mockito.mock(FilterConfig.class); Mockito.when(config.getinitParameter("management.operation.return")). thenReturn("true"); Mockito.when(config.getinitParameter(AuthenticationFilter.AUTH_TYPE)).thenReturn( DummyAuthenticationHandler.class.getName()); Mockito.when(config.getinitParameter(AuthenticationFilter.SIGNATURE_SECRET)).thenReturn("secret"); Mockito.when(config.getinitParameterNames()).thenReturn( new Vector<String>( Arrays.asList(AuthenticationFilter.AUTH_TYPE,"management.operation.return")).elements()); getMockedServletContextWithStringSigner(config); filter.init(config); AuthenticationToken token = new AuthenticationToken("u","invalidtype"); token.setExpires(System.currentTimeMillis() + TOKEN_VALIDITY_SEC); SignerSecretProvider secretProvider = StringSignerSecretProviderCreator.newStringSignerSecretProvider(); Properties secretProviderProps = new Properties(); secretProviderProps.setProperty( AuthenticationFilter.SIGNATURE_SECRET,tokenSigned); HttpServletRequest request = Mockito.mock(HttpServletRequest.class); Mockito.when(request.getCookies()).thenReturn(new Cookie[]{cookie}); boolean Failed = false; try { filter.getToken(request); } catch (AuthenticationException ex) { Assert.assertEquals("Invalid AuthenticationToken type",ex.getMessage()); Failed = true; } finally { Assert.assertTrue("token not invalid type",Failed); } } finally { filter.destroy(); } }
@Test public void testDoFilterauthenticatedExpired() throws Exception { String secret = "secret"; AuthenticationFilter filter = new AuthenticationFilter(); try { FilterConfig config = Mockito.mock(FilterConfig.class); Mockito.when(config.getinitParameter("management.operation.return")). thenReturn("true"); Mockito.when(config.getinitParameter(AuthenticationFilter.AUTH_TYPE)).thenReturn( DummyAuthenticationHandler.class.getName()); Mockito.when(config.getinitParameter(AuthenticationFilter.SIGNATURE_SECRET)).thenReturn( secret); Mockito.when(config.getinitParameterNames()).thenReturn( new Vector<String>( Arrays.asList(AuthenticationFilter.AUTH_TYPE,"management.operation.return")).elements()); getMockedServletContextWithStringSigner(config); filter.init(config); HttpServletRequest request = Mockito.mock(HttpServletRequest.class); Mockito.when(request.getRequestURL()).thenReturn(new StringBuffer("http://foo:8080/bar")); AuthenticationToken token = new AuthenticationToken("u",secret); secretProvider.init(secretProviderProps,tokenSigned); Mockito.when(request.getCookies()).thenReturn(new Cookie[]{cookie}); HttpServletResponse response = Mockito.mock(HttpServletResponse.class); Mockito.when(response.containsHeader("WWW-Authenticate")).thenReturn(true); FilterChain chain = Mockito.mock(FilterChain.class); verifyUnauthorized(filter,request,chain); } finally { filter.destroy(); } }
@Test public void testDoFilterauthenticatedInvalidType() throws Exception { String secret = "secret"; AuthenticationFilter filter = new AuthenticationFilter(); try { FilterConfig config = Mockito.mock(FilterConfig.class); Mockito.when(config.getinitParameter("management.operation.return")). thenReturn("true"); Mockito.when(config.getinitParameter(AuthenticationFilter.AUTH_TYPE)).thenReturn( DummyAuthenticationHandler.class.getName()); Mockito.when(config.getinitParameter(AuthenticationFilter.SIGNATURE_SECRET)).thenReturn( secret); Mockito.when(config.getinitParameterNames()).thenReturn( new Vector<String>( Arrays.asList(AuthenticationFilter.AUTH_TYPE,chain); } finally { filter.destroy(); } }
@Test public void testManagementOperation() throws Exception { AuthenticationFilter filter = new AuthenticationFilter(); try { FilterConfig config = Mockito.mock(FilterConfig.class); Mockito.when(config.getinitParameter("management.operation.return")). thenReturn("false"); Mockito.when(config.getinitParameter(AuthenticationFilter.AUTH_TYPE)). thenReturn(DummyAuthenticationHandler.class.getName()); Mockito.when(config.getinitParameterNames()).thenReturn( new Vector<String>( Arrays.asList(AuthenticationFilter.AUTH_TYPE,"management.operation.return")).elements()); getMockedServletContextWithStringSigner(config); filter.init(config); HttpServletRequest request = Mockito.mock(HttpServletRequest.class); Mockito.when(request.getRequestURL()). thenReturn(new StringBuffer("http://foo:8080/bar")); HttpServletResponse response = Mockito.mock(HttpServletResponse.class); FilterChain chain = Mockito.mock(FilterChain.class); filter.doFilter(request,chain); Mockito.verify(response).setStatus(HttpServletResponse.SC_ACCEPTED); Mockito.verifyNoMoreInteractions(response); Mockito.reset(request); Mockito.reset(response); AuthenticationToken token = new AuthenticationToken("u","t"); token.setExpires(System.currentTimeMillis() + TOKEN_VALIDITY_SEC); SignerSecretProvider secretProvider = StringSignerSecretProviderCreator.newStringSignerSecretProvider(); Properties secretProviderProps = new Properties(); secretProviderProps.setProperty( AuthenticationFilter.SIGNATURE_SECRET,TOKEN_VALIDITY_SEC); Signer signer = new Signer(secretProvider); String tokenSigned = signer.sign(token.toString()); Cookie cookie = new Cookie(AuthenticatedURL.AUTH_COOKIE,tokenSigned); Mockito.when(request.getCookies()).thenReturn(new Cookie[]{cookie}); filter.doFilter(request,chain); Mockito.verify(response).setStatus(HttpServletResponse.SC_ACCEPTED); Mockito.verifyNoMoreInteractions(response); } finally { filter.destroy(); } }
@Test public void testGetTokenExpired() throws Exception { AuthenticationFilter filter = new AuthenticationFilter(); try { FilterConfig config = Mockito.mock(FilterConfig.class); Mockito.when(config.getinitParameter("management.operation.return")).thenReturn("true"); Mockito.when(config.getinitParameter(AuthenticationFilter.AUTH_TYPE)).thenReturn( DummyAuthenticationHandler.class.getName()); Mockito.when(config.getinitParameter(AuthenticationFilter.SIGNATURE_SECRET)).thenReturn("secret"); Mockito.when(config.getinitParameterNames()).thenReturn( new Vector<String>( Arrays.asList(AuthenticationFilter.AUTH_TYPE,Failed); } } finally { filter.destroy(); } }
@Test public void testGetTokenInvalidType() throws Exception { AuthenticationFilter filter = new AuthenticationFilter(); try { FilterConfig config = Mockito.mock(FilterConfig.class); Mockito.when(config.getinitParameter("management.operation.return")). thenReturn("true"); Mockito.when(config.getinitParameter(AuthenticationFilter.AUTH_TYPE)).thenReturn( DummyAuthenticationHandler.class.getName()); Mockito.when(config.getinitParameter(AuthenticationFilter.SIGNATURE_SECRET)).thenReturn("secret"); Mockito.when(config.getinitParameterNames()).thenReturn( new Vector<String>( Arrays.asList(AuthenticationFilter.AUTH_TYPE,Failed); } } finally { filter.destroy(); } }
@Test public void testDoFilterauthenticatedExpired() throws Exception { String secret = "secret"; AuthenticationFilter filter = new AuthenticationFilter(); try { FilterConfig config = Mockito.mock(FilterConfig.class); Mockito.when(config.getinitParameter("management.operation.return")). thenReturn("true"); Mockito.when(config.getinitParameter(AuthenticationFilter.AUTH_TYPE)).thenReturn( DummyAuthenticationHandler.class.getName()); Mockito.when(config.getinitParameter(AuthenticationFilter.SIGNATURE_SECRET)).thenReturn( secret); Mockito.when(config.getinitParameterNames()).thenReturn( new Vector<String>( Arrays.asList(AuthenticationFilter.AUTH_TYPE,chain); } finally { filter.destroy(); } }
private void _testDoFilterauthenticationMaxInactiveInterval(long maxInactives,long expires,boolean authorized) throws Exception { String secret = "secret"; AuthenticationFilter filter = new AuthenticationFilter(); try { FilterConfig config = Mockito.mock(FilterConfig.class); Mockito.when(config.getinitParameter("management.operation.return")). thenReturn("true"); Mockito.when(config.getinitParameter( AuthenticationFilter.AUTH_TYPE)).thenReturn( DummyAuthenticationHandler.class.getName()); Mockito.when(config.getinitParameter( AuthenticationFilter.SIGNATURE_SECRET)).thenReturn(secret); Mockito.when(config.getinitParameterNames()).thenReturn( new Vector<String>( Arrays.asList(AuthenticationFilter.AUTH_TYPE,"management.operation.return")).elements()); getMockedServletContextWithStringSigner(config); filter.init(config); HttpServletRequest request = Mockito.mock(HttpServletRequest.class); Mockito.when(request.getRequestURL()).thenReturn( new StringBuffer("http://foo:8080/bar")); AuthenticationToken token = new AuthenticationToken("u",DummyAuthenticationHandler.TYPE); token.setMaxInactives(maxInactives); token.setExpires(expires); SignerSecretProvider secretProvider = StringSignerSecretProviderCreator.newStringSignerSecretProvider(); Properties secretProviderProps = new Properties(); secretProviderProps.setProperty( AuthenticationFilter.SIGNATURE_SECRET,tokenSigned); Mockito.when(request.getCookies()).thenReturn(new Cookie[]{cookie}); HttpServletResponse response = Mockito.mock(HttpServletResponse.class); Mockito.when(response.containsHeader("WWW-Authenticate")) .thenReturn(true); FilterChain chain = Mockito.mock(FilterChain.class); if (authorized) { verifyAuthorized(filter,chain); } else { verifyUnauthorized(filter,chain); } } finally { filter.destroy(); } }
@Test public void testDoFilterauthenticatedInvalidType() throws Exception { String secret = "secret"; AuthenticationFilter filter = new AuthenticationFilter(); try { FilterConfig config = Mockito.mock(FilterConfig.class); Mockito.when(config.getinitParameter("management.operation.return")). thenReturn("true"); Mockito.when(config.getinitParameter(AuthenticationFilter.AUTH_TYPE)).thenReturn( DummyAuthenticationHandler.class.getName()); Mockito.when(config.getinitParameter(AuthenticationFilter.SIGNATURE_SECRET)).thenReturn( secret); Mockito.when(config.getinitParameterNames()).thenReturn( new Vector<String>( Arrays.asList(AuthenticationFilter.AUTH_TYPE,chain); } finally { filter.destroy(); } }
@Test public void testManagementOperation() throws Exception { AuthenticationFilter filter = new AuthenticationFilter(); try { FilterConfig config = Mockito.mock(FilterConfig.class); Mockito.when(config.getinitParameter("management.operation.return")). thenReturn("false"); Mockito.when(config.getinitParameter(AuthenticationFilter.AUTH_TYPE)). thenReturn(DummyAuthenticationHandler.class.getName()); Mockito.when(config.getinitParameterNames()).thenReturn( new Vector<String>( Arrays.asList(AuthenticationFilter.AUTH_TYPE,chain); Mockito.verify(response).setStatus(HttpServletResponse.SC_ACCEPTED); Mockito.verifyNoMoreInteractions(response); } finally { filter.destroy(); } }
@Test public void testGetTokenExpired() throws Exception { AuthenticationFilter filter = new AuthenticationFilter(); try { FilterConfig config = Mockito.mock(FilterConfig.class); Mockito.when(config.getinitParameter("management.operation.return")).thenReturn("true"); Mockito.when(config.getinitParameter(AuthenticationFilter.AUTH_TYPE)).thenReturn( DummyAuthenticationHandler.class.getName()); Mockito.when(config.getinitParameter(AuthenticationFilter.SIGNATURE_SECRET)).thenReturn("secret"); Mockito.when(config.getinitParameterNames()).thenReturn( new Vector<String>( Arrays.asList(AuthenticationFilter.AUTH_TYPE,Failed); } } finally { filter.destroy(); } }
@Test public void testGetTokenInvalidType() throws Exception { AuthenticationFilter filter = new AuthenticationFilter(); try { FilterConfig config = Mockito.mock(FilterConfig.class); Mockito.when(config.getinitParameter("management.operation.return")). thenReturn("true"); Mockito.when(config.getinitParameter(AuthenticationFilter.AUTH_TYPE)).thenReturn( DummyAuthenticationHandler.class.getName()); Mockito.when(config.getinitParameter(AuthenticationFilter.SIGNATURE_SECRET)).thenReturn("secret"); Mockito.when(config.getinitParameterNames()).thenReturn( new Vector<String>( Arrays.asList(AuthenticationFilter.AUTH_TYPE,Failed); } } finally { filter.destroy(); } }
@Test public void testDoFilterauthenticatedExpired() throws Exception { String secret = "secret"; AuthenticationFilter filter = new AuthenticationFilter(); try { FilterConfig config = Mockito.mock(FilterConfig.class); Mockito.when(config.getinitParameter("management.operation.return")). thenReturn("true"); Mockito.when(config.getinitParameter(AuthenticationFilter.AUTH_TYPE)).thenReturn( DummyAuthenticationHandler.class.getName()); Mockito.when(config.getinitParameter(AuthenticationFilter.SIGNATURE_SECRET)).thenReturn( secret); Mockito.when(config.getinitParameterNames()).thenReturn( new Vector<String>( Arrays.asList(AuthenticationFilter.AUTH_TYPE,chain); } finally { filter.destroy(); } }
@Test public void testDoFilterauthenticatedInvalidType() throws Exception { String secret = "secret"; AuthenticationFilter filter = new AuthenticationFilter(); try { FilterConfig config = Mockito.mock(FilterConfig.class); Mockito.when(config.getinitParameter("management.operation.return")). thenReturn("true"); Mockito.when(config.getinitParameter(AuthenticationFilter.AUTH_TYPE)).thenReturn( DummyAuthenticationHandler.class.getName()); Mockito.when(config.getinitParameter(AuthenticationFilter.SIGNATURE_SECRET)).thenReturn( secret); Mockito.when(config.getinitParameterNames()).thenReturn( new Vector<String>( Arrays.asList(AuthenticationFilter.AUTH_TYPE,chain); } finally { filter.destroy(); } }
@Test public void testManagementOperation() throws Exception { AuthenticationFilter filter = new AuthenticationFilter(); try { FilterConfig config = Mockito.mock(FilterConfig.class); Mockito.when(config.getinitParameter("management.operation.return")). thenReturn("false"); Mockito.when(config.getinitParameter(AuthenticationFilter.AUTH_TYPE)). thenReturn(DummyAuthenticationHandler.class.getName()); Mockito.when(config.getinitParameterNames()).thenReturn( new Vector<String>( Arrays.asList(AuthenticationFilter.AUTH_TYPE,chain); Mockito.verify(response).setStatus(HttpServletResponse.SC_ACCEPTED); Mockito.verifyNoMoreInteractions(response); } finally { filter.destroy(); } }
@Test @TestDir @TestJetty @TestHdfs public void testDelegationTokenoperations() throws Exception { createHttpFSServer(true); URL url = new URL(TestJettyHelper.getJettyURL(),"/webhdfs/v1/?op=GETHOMEDIRECTORY"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); Assert.assertEquals(HttpURLConnection.HTTP_UNAUTHORIZED,conn.getResponseCode()); AuthenticationToken token = new AuthenticationToken("u",HttpFSKerberosAuthenticationHandlerForTesting.TYPE); token.setExpires(System.currentTimeMillis() + 100000000); SignerSecretProvider secretProvider = StringSignerSecretProviderCreator.newStringSignerSecretProvider(); Properties secretProviderProps = new Properties(); secretProviderProps.setProperty(AuthenticationFilter.SIGNATURE_SECRET,-1); Signer signer = new Signer(secretProvider); String tokenSigned = signer.sign(token.toString()); url = new URL(TestJettyHelper.getJettyURL(),"/webhdfs/v1/?op=GETHOMEDIRECTORY"); conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("Cookie",AuthenticatedURL.AUTH_COOKIE + "=" + tokenSigned); Assert.assertEquals(HttpURLConnection.HTTP_OK,conn.getResponseCode()); url = new URL(TestJettyHelper.getJettyURL(),"/webhdfs/v1/?op=GETDELEGATIONTOKEN"); conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("Cookie",conn.getResponseCode()); JSONObject json = (JSONObject) new JSONParser() .parse(new InputStreamReader(conn.getInputStream())); json = (JSONObject) json .get(HttpFSKerberosAuthenticator.DELEGATION_TOKEN_JSON); String tokenStr = (String) json .get(HttpFSKerberosAuthenticator.DELEGATION_TOKEN_URL_STRING_JSON); url = new URL(TestJettyHelper.getJettyURL(),"/webhdfs/v1/?op=GETHOMEDIRECTORY&delegation=" + tokenStr); conn = (HttpURLConnection) url.openConnection(); Assert.assertEquals(HttpURLConnection.HTTP_OK,"/webhdfs/v1/?op=RENEWDELEGATIONTOKEN&token=" + tokenStr); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("PUT"); Assert.assertEquals(HttpURLConnection.HTTP_UNAUTHORIZED,"/webhdfs/v1/?op=RENEWDELEGATIONTOKEN&token=" + tokenStr); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("PUT"); conn.setRequestProperty("Cookie","/webhdfs/v1/?op=CANCELDELEGATIONTOKEN&token=" + tokenStr); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("PUT"); Assert.assertEquals(HttpURLConnection.HTTP_OK,"/webhdfs/v1/?op=GETHOMEDIRECTORY&delegation=" + tokenStr); conn = (HttpURLConnection) url.openConnection(); Assert .assertEquals(HttpURLConnection.HTTP_FORBIDDEN,conn.getResponseCode()); }
@Test public void testGetTokenExpired() throws Exception { AuthenticationFilter filter = new AuthenticationFilter(); try { FilterConfig config = Mockito.mock(FilterConfig.class); Mockito.when(config.getinitParameter("management.operation.return")).thenReturn("true"); Mockito.when(config.getinitParameter(AuthenticationFilter.AUTH_TYPE)).thenReturn( DummyAuthenticationHandler.class.getName()); Mockito.when(config.getinitParameter(AuthenticationFilter.SIGNATURE_SECRET)).thenReturn("secret"); Mockito.when(config.getinitParameterNames()).thenReturn( new Vector<String>( Arrays.asList(AuthenticationFilter.AUTH_TYPE,Failed); } } finally { filter.destroy(); } }
@Test public void testGetTokenInvalidType() throws Exception { AuthenticationFilter filter = new AuthenticationFilter(); try { FilterConfig config = Mockito.mock(FilterConfig.class); Mockito.when(config.getinitParameter("management.operation.return")). thenReturn("true"); Mockito.when(config.getinitParameter(AuthenticationFilter.AUTH_TYPE)).thenReturn( DummyAuthenticationHandler.class.getName()); Mockito.when(config.getinitParameter(AuthenticationFilter.SIGNATURE_SECRET)).thenReturn("secret"); Mockito.when(config.getinitParameterNames()).thenReturn( new Vector<String>( Arrays.asList(AuthenticationFilter.AUTH_TYPE,Failed); } } finally { filter.destroy(); } }
@Test public void testDoFilterauthenticatedExpired() throws Exception { String secret = "secret"; AuthenticationFilter filter = new AuthenticationFilter(); try { FilterConfig config = Mockito.mock(FilterConfig.class); Mockito.when(config.getinitParameter("management.operation.return")). thenReturn("true"); Mockito.when(config.getinitParameter(AuthenticationFilter.AUTH_TYPE)).thenReturn( DummyAuthenticationHandler.class.getName()); Mockito.when(config.getinitParameter(AuthenticationFilter.SIGNATURE_SECRET)).thenReturn( secret); Mockito.when(config.getinitParameterNames()).thenReturn( new Vector<String>( Arrays.asList(AuthenticationFilter.AUTH_TYPE,chain); } finally { filter.destroy(); } }
private void _testDoFilterauthenticationMaxInactiveInterval(long maxInactivesInToken,long maxInactivesOnServer,boolean authorized,boolean newCookie) throws Exception { String secret = "secret"; AuthenticationFilter filter = new AuthenticationFilter(); try { FilterConfig config = Mockito.mock(FilterConfig.class); Mockito.when(config.getinitParameter("management.operation.return")). thenReturn("true"); Mockito.when(config.getinitParameter( AuthenticationFilter.AUTH_TYPE)).thenReturn( DummyAuthenticationHandler.class.getName()); Mockito.when(config.getinitParameter( AuthenticationFilter.SIGNATURE_SECRET)).thenReturn(secret); Mockito.when(config.getinitParameter( AuthenticationFilter.AUTH_TOKEN_MAX_INACTIVE_INTERVAL)).thenReturn( Long.toString(maxInactivesOnServer)); Mockito.when(config.getinitParameterNames()).thenReturn( new Vector<String>( Arrays.asList(AuthenticationFilter.AUTH_TYPE,AuthenticationFilter.AUTH_TOKEN_MAX_INACTIVE_INTERVAL,DummyAuthenticationHandler.TYPE); token.setMaxInactives(maxInactivesInToken); token.setExpires(expires); SignerSecretProvider secretProvider = StringSignerSecretProviderCreator.newStringSignerSecretProvider(); Properties secretProviderProps = new Properties(); secretProviderProps.setProperty( AuthenticationFilter.SIGNATURE_SECRET,chain,newCookie); } else { verifyUnauthorized(filter,chain); } } finally { filter.destroy(); } }
private static void verifyAuthorized(AuthenticationFilter filter,FilterChain chain,boolean newCookie) throws Exception { final Map<String,chain); if (newCookie) { // a new cookie should be dropped when maxInactiveInterval is enabled String v = cookieMap.get(AuthenticatedURL.AUTH_COOKIE); Assert.assertNotNull("cookie missing",v); Assert.assertTrue(v.contains("u=") && v.contains("p=") && v.contains ("t=") && v.contains("i=") && v.contains("e=") && v.contains("s=")); Mockito.verify(chain).doFilter(Mockito.any(ServletRequest.class),Mockito.any(ServletResponse.class)); SignerSecretProvider secretProvider = StringSignerSecretProviderCreator.newStringSignerSecretProvider(); Properties secretProviderProps = new Properties(); secretProviderProps.setProperty( AuthenticationFilter.SIGNATURE_SECRET,TOKEN_VALIDITY_SEC); Signer signer = new Signer(secretProvider); String value = signer.verifyAndExtract(v); AuthenticationToken token = AuthenticationToken.parse(value); assertthat(token.getMaxInactives(),not(0L)); assertthat(token.getExpires(),not(0L)); Assert.assertFalse("Token is expired.",token.isExpired()); } else { //make sure that no auth cookie is dropped. //For unauthorized response,auth cookie is dropped with empty value Assert.assertTrue("cookie is present",!cookieMap.containsKey(AuthenticatedURL.AUTH_COOKIE)); } }
@Test public void testDoFilterauthenticatedInvalidType() throws Exception { String secret = "secret"; AuthenticationFilter filter = new AuthenticationFilter(); try { FilterConfig config = Mockito.mock(FilterConfig.class); Mockito.when(config.getinitParameter("management.operation.return")). thenReturn("true"); Mockito.when(config.getinitParameter(AuthenticationFilter.AUTH_TYPE)).thenReturn( DummyAuthenticationHandler.class.getName()); Mockito.when(config.getinitParameter(AuthenticationFilter.SIGNATURE_SECRET)).thenReturn( secret); Mockito.when(config.getinitParameterNames()).thenReturn( new Vector<String>( Arrays.asList(AuthenticationFilter.AUTH_TYPE,chain); } finally { filter.destroy(); } }
org.apache.hadoop.security.authentication.util.ZKSignerSecretProvider的实例源码
@Override protected void initializeAuthHandler(String authHandlerClassName,FilterConfig filterConfig) throws servletexception { // A single CuratorFramework should be used for a ZK cluster. // If the ZKSignerSecretProvider has already created it,it has to // be set here... to be used by the ZKDelegationTokenSecretManager ZKDelegationTokenSecretManager.setCurator((CuratorFramework) filterConfig.getServletContext().getAttribute(ZKSignerSecretProvider. ZOOKEEPER_SIGNER_SECRET_PROVIDER_CURATOR_CLIENT_ATTRIBUTE)); super.initializeAuthHandler(authHandlerClassName,filterConfig); ZKDelegationTokenSecretManager.setCurator(null); }
@Override protected void initializeAuthHandler(String authHandlerClassName,filterConfig); ZKDelegationTokenSecretManager.setCurator(null); }
@Override protected void initializeAuthHandler(String authHandlerClassName,filterConfig); ZKDelegationTokenSecretManager.setCurator(null); }
@Override protected void initializeAuthHandler(String authHandlerClassName,filterConfig); ZKDelegationTokenSecretManager.setCurator(null); }
@Override protected void initializeAuthHandler(String authHandlerClassName,filterConfig); ZKDelegationTokenSecretManager.setCurator(null); }
@SuppressWarnings("unchecked") private Class<? extends SignerSecretProvider> getProviderClass(Properties config) throws servletexception { String providerClassName; String signerSecretProviderName = config.getProperty(SIGNER_SECRET_PROVIDER,null); // fallback to old behavior if (signerSecretProviderName == null) { String signatureSecret = config.getProperty(SIGNATURE_SECRET,null); if (signatureSecret != null) { providerClassName = StringSignerSecretProvider.class.getName(); } else { providerClassName = RandomSignerSecretProvider.class.getName(); randomSecret = true; } } else { if ("random".equals(signerSecretProviderName)) { providerClassName = RandomSignerSecretProvider.class.getName(); randomSecret = true; } else if ("string".equals(signerSecretProviderName)) { providerClassName = StringSignerSecretProvider.class.getName(); } else if ("zookeeper".equals(signerSecretProviderName)) { providerClassName = ZKSignerSecretProvider.class.getName(); } else { providerClassName = signerSecretProviderName; customSecretProvider = true; } } try { return (Class<? extends SignerSecretProvider>) Thread.currentThread(). getContextClassLoader().loadClass(providerClassName); } catch (ClassNotFoundException ex) { throw new servletexception(ex); } }
@Override protected void initializeAuthHandler(String authHandlerClassName,filterConfig); ZKDelegationTokenSecretManager.setCurator(null); }
org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration.WebMvcAutoConfigurationAdapter的实例源码
@Test public void overrideMessageCodesFormat() throws Exception { load(AllResources.class,"spring.mvc.messageCodesResolverFormat:POSTFIX_ERROR_CODE"); assertthat(this.context.getBean(WebMvcAutoConfigurationAdapter.class) .getMessageCodesResolver()).isNotNull(); }
@Test public void overrideMessageCodesFormat() throws Exception { load(AllResources.class,"spring.mvc.messageCodesResolverFormat:POSTFIX_ERROR_CODE"); assertthat(this.context.getBean(WebMvcAutoConfigurationAdapter.class) .getMessageCodesResolver()).isNotNull(); }
@Test public void overrideMessageCodesFormat() throws Exception { load(AllResources.class,"spring.mvc.messageCodesResolverFormat:POSTFIX_ERROR_CODE"); assertNotNull(this.context.getBean(WebMvcAutoConfigurationAdapter.class) .getMessageCodesResolver()); }
@Test public void noMessageCodesResolver() throws Exception { load(AllResources.class); assertthat(this.context.getBean(WebMvcAutoConfigurationAdapter.class) .getMessageCodesResolver()).isNull(); }
@Test public void noMessageCodesResolver() throws Exception { load(AllResources.class); assertthat(this.context.getBean(WebMvcAutoConfigurationAdapter.class) .getMessageCodesResolver()).isNull(); }
@Test public void noMessageCodesResolver() throws Exception { load(AllResources.class); assertNull(this.context.getBean(WebMvcAutoConfigurationAdapter.class) .getMessageCodesResolver()); }
org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter的实例源码
@Override public ConditionOutcome getMatchOutcome(ConditionContext context,AnnotatedTypeMetadata Metadata) { String[] enablers = context.getbeanfactory() .getBeanNamesForAnnotation(EnableOAuth2Sso.class); ConditionMessage.Builder message = ConditionMessage .forCondition("@EnableOAuth2Sso Condition"); for (String name : enablers) { if (context.getbeanfactory().isTypeMatch(name,WebSecurityConfigurerAdapter.class)) { return ConditionOutcome.match(message .found("@EnableOAuth2Sso annotation on WebSecurityConfigurerAdapter") .items(name)); } } return ConditionOutcome.noMatch(message.didNotFind( "@EnableOAuth2Sso annotation " + "on any WebSecurityConfigurerAdapter") .atAll()); }
@Bean public WebSecurityConfigurerAdapter securityConfigBean(){ return new WebSecurityConfigurerAdapter() { @Override protected void configure(HttpSecurity http) throws Exception { // We need this to prevent the browser from popping up a dialog on a 401 http .httpBasic() .and() .authorizeRequests() .antMatchers(HttpMethod.GET,"/posts/**").permitAll() .antMatchers(HttpMethod.DELETE,"/posts/**").hasRole("ADMIN") .anyRequest().authenticated() .and() .csrf().disable(); } }; }
@Bean WebSecurityConfigurerAdapter webSecurityConfigurerAdapter() { return new WebSecurityConfigurerAdapter() { @Override protected void configure(HttpSecurity http) throws Exception { http .csrf().disable() // enables HTTP GET for /logout,not recommended in prod .authorizeRequests() .antMatchers("/b/**").hasAnyAuthority("USER") // hasRole(ADMIN) == hasAuthority(ROLE_ADMIN) .antMatchers("/books/**").hasRole("ADMIN") .anyRequest().authenticated() .and().formLogin() .and().logout().permitAll(); } }; }
@Bean public WebSecurityConfigurerAdapter applicationSecurity() { return new WebSecurityConfigurerAdapter() { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests().anyRequest().permitAll().and().csrf().disable(); //oops? } // // @Override // protected void configure(AuthenticationManagerBuilder auth) throws Exception { // auth.inMemoryAuthentication().withUser("admin").password("admin") // .roles("ADMIN","USER").and().withUser("user").password("user") // .roles("USER"); // } }; }
@Override public Object postProcessAfterInitialization(Object bean,String beanName) throws BeansException { if (this.configType.isAssignableFrom(bean.getClass()) && bean instanceof WebSecurityConfigurerAdapter) { ProxyFactory factory = new ProxyFactory(); factory.setTarget(bean); factory.addAdvice(new SsoSecurityAdapter(this.applicationContext)); bean = factory.getProxy(); } return bean; }
@Override public Object invoke(MethodInvocation invocation) throws Throwable { if (invocation.getmethod().getName().equals("init")) { Method method = ReflectionUtils .findMethod(WebSecurityConfigurerAdapter.class,"getHttp"); ReflectionUtils.makeAccessible(method); HttpSecurity http = (HttpSecurity) ReflectionUtils.invokeMethod(method,invocation.getThis()); this.configurer.configure(http); } return invocation.proceed(); }
/** * Checks whether beans are registered after auto configuration class has been registered */ @Test public void registerJwtAutoConfiguration() { this.context.register(SecurityProperties.class); this.context.register(JwtAutoConfiguration.class); this.context.refresh(); //assert this.context.getBean(TokenProvider.class); this.context.getBean(PasswordEncoder.class); this.context.getBean(UserDetailsService.class); this.context.getBean(SecurityEvaluationContextExtension.class); this.context.getBean(WebSecurityConfigurerAdapter.class); }
/** * Expects not to have {@link WebSecurityConfigurerAdapter} in context if property is set to false */ @Test(expected = NoSuchBeanDeFinitionException.class) public void propertyAutoSecuritydisabled() { this.context.register(SecurityProperties.class); this.context.register(JwtAutoConfiguration.class); EnvironmentTestUtils.addEnvironment(this.context,"com.github.cobrijani.jwt.enabled:false"); this.context.refresh(); //assert this.context.getBean(WebSecurityConfigurerAdapter.class); }
@Override public Object postProcessAfterInitialization(Object bean,String beanName) throws BeansException { if (this.configType.isAssignableFrom(bean.getClass()) && bean instanceof WebSecurityConfigurerAdapter) { ProxyFactory factory = new ProxyFactory(); factory.setTarget(bean); factory.addAdvice(new SsoSecurityAdapter(this.applicationContext)); bean = factory.getProxy(); } return bean; }
@Override public Object invoke(MethodInvocation invocation) throws Throwable { if (invocation.getmethod().getName().equals("init")) { Method method = ReflectionUtils .findMethod(WebSecurityConfigurerAdapter.class,invocation.getThis()); this.configurer.configure(http); } return invocation.proceed(); }
@Override public ConditionOutcome getMatchOutcome(ConditionContext context,AnnotatedTypeMetadata Metadata) { String[] enablers = context.getbeanfactory() .getBeanNamesForAnnotation(EnableOAuth2Sso.class); for (String name : enablers) { if (context.getbeanfactory().isTypeMatch(name,WebSecurityConfigurerAdapter.class)) { return ConditionOutcome.match( "found @EnableOAuth2Sso on a WebSecurityConfigurerAdapter"); } } return ConditionOutcome.noMatch( "found no @EnableOAuth2Sso on a WebSecurityConfigurerAdapter"); }
@Override public ConditionOutcome getMatchOutcome(ConditionContext context,WebSecurityConfigurerAdapter.class)) { return ConditionOutcome.noMatch( "found @EnableOAuth2Sso on a WebSecurityConfigurerAdapter"); } } return ConditionOutcome .match("found no @EnableOAuth2Sso on a WebSecurityConfigurerAdapter"); }
@SuppressWarnings("unchecked") @Override protected <T extends WebSecurityConfigurerAdapter> Class<T> getSpringSecurityConfigClass(IServerContext context) { if (context.equals(PServerContext.WORKLIST)) { return (Class<T>) SecurityConfigs.Casanalise.class; } else if (context.equals(PServerContext.REQUIREMENT)) { return (Class<T>) SecurityConfigs.CASPeticionamento.class; } else if (context.equals(PServerContext.ADMINISTRATION)) { return (Class<T>) SecurityConfigs.AdministrationSecurity.class; } return null; }
public void init(ServletContext ctx,AnnotationConfigWebApplicationContext applicationContext,String springMVCServletMapping,IServerContext[] serverContexts) { addRestSecurity(applicationContext); addSpringSecurityFilter(ctx,applicationContext,springMVCServletMapping); for (IServerContext context : serverContexts) { logger.info(SINGULAR_Security,"Securing (Spring Security) context:",context.getcontextpath()); Class<WebSecurityConfigurerAdapter> config = getSpringSecurityConfigClass(context); if (config != null) { applicationContext.register(config); addlogoutFilter(ctx,springMVCServletMapping,context); } } }
@Override public Object postProcessAfterInitialization(Object bean,String beanName) throws BeansException { if (this.configType.isAssignableFrom(bean.getClass()) && bean instanceof WebSecurityConfigurerAdapter) { ProxyFactory factory = new ProxyFactory(); factory.setTarget(bean); factory.addAdvice(new SsoSecurityAdapter(this.applicationContext)); bean = factory.getProxy(); } return bean; }
@Override public Object invoke(MethodInvocation invocation) throws Throwable { if (invocation.getmethod().getName().equals("init")) { Method method = ReflectionUtils .findMethod(WebSecurityConfigurerAdapter.class,invocation.getThis()); this.configurer.configure(http); } return invocation.proceed(); }
@Override public ConditionOutcome getMatchOutcome(ConditionContext context,WebSecurityConfigurerAdapter.class)) { return ConditionOutcome.match( "found @EnableOAuth2Sso on a WebSecurityConfigurerAdapter"); } } return ConditionOutcome.noMatch( "found no @EnableOAuth2Sso on a WebSecurityConfigurerAdapter"); }
@Override public ConditionOutcome getMatchOutcome(ConditionContext context,WebSecurityConfigurerAdapter.class)) { return ConditionOutcome.noMatch( "found @EnableOAuth2Sso on a WebSecurityConfigurerAdapter"); } } return ConditionOutcome .match("found no @EnableOAuth2Sso on a WebSecurityConfigurerAdapter"); }
@Bean public WebSecurityConfigurerAdapter webSecurityConfigure(){ return new WebSecurityConfigurerAdapter() { @Override protected void configure(HttpSecurity http) throws Exception { // @formatter:off http .authorizeRequests() .antMatchers("/api/signup","/api/users/username-check") .permitAll() .and() .authorizeRequests() .regexMatchers(HttpMethod.GET,"^/api/users/[\\d]*(\\/)?$").authenticated() .regexMatchers(HttpMethod.GET,"^/api/users(\\/)?(\\?.+)?$").hasRole("ADMIN") .regexMatchers(HttpMethod.DELETE,"^/api/users/[\\d]*(\\/)?$").hasRole("ADMIN") .regexMatchers(HttpMethod.POST,"^/api/users(\\/)?$").hasRole("ADMIN") .and() .authorizeRequests() .antMatchers("/api/**").authenticated() .and() .authorizeRequests() .anyRequest().permitAll() .and() .sessionManagement() .sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() .httpBasic() .and() .csrf() .disable(); // @formatter:on } }; }
@Override public Object postProcessAfterInitialization(Object bean,String beanName) throws BeansException { if (this.configType.isAssignableFrom(bean.getClass()) && bean instanceof WebSecurityConfigurerAdapter) { ProxyFactory factory = new ProxyFactory(); factory.setTarget(bean); factory.addAdvice(new SsoSecurityAdapter(this.beanfactory)); bean = factory.getProxy(); } return bean; }
@Override public Object invoke(MethodInvocation invocation) throws Throwable { if (invocation.getmethod().getName().equals("init")) { Method method = ReflectionUtils .findMethod(WebSecurityConfigurerAdapter.class,invocation.getThis()); this.configurer.configure(http); } return invocation.proceed(); }
@Override public ConditionOutcome getMatchOutcome(ConditionContext context,WebSecurityConfigurerAdapter.class)) { return ConditionOutcome.match( "found @EnableOAuth2Sso on a WebSecurityConfigurerAdapter"); } } return ConditionOutcome.noMatch( "found no @EnableOAuth2Sso on a WebSecurityConfigurerAdapter"); }
@Override public ConditionOutcome getMatchOutcome(ConditionContext context,WebSecurityConfigurerAdapter.class)) { return ConditionOutcome.noMatch( "found @EnableOAuth2Sso on a WebSecurityConfigurerAdapter"); } } return ConditionOutcome .match("found no @EnableOAuth2Sso on a WebSecurityConfigurerAdapter"); }
@Bean public WebSecurityConfigurerAdapter secureConfigurer() { return new WebSecurityConfigurerAdapterImpl(); }
@Bean public WebSecurityConfigurerAdapter h2ConsoleSecurityConfigurer() { return new H2ConsoleSecurityConfigurer(); }
@Override protected <T extends WebSecurityConfigurerAdapter> Class<T> getSpringSecurityConfigClass(IServerContext context) { return (Class<T>) StudioSecurity.class; }
@Bean public WebSecurityConfigurerAdapter h2ConsoleSecurityConfigurer() { return new H2ConsoleSecurityConfigurer(); }
@Bean public WebSecurityConfigurerAdapter h2ConsoleSecurityConfigurer() { return new H2ConsoleSecurityConfigurer(); }
/** * disable csrf * Allows anonymous request * * @return */ @Bean @Autowired WebSecurityConfigurerAdapter webSecurityConfigurerAdapter() { return new WebSecurityConfigurerAdapterImpl(); }
protected abstract <T extends WebSecurityConfigurerAdapter> Class<T> getSpringSecurityConfigClass(IServerContext context);
我们今天的关于将多个WebSecurityConfigurerAdapter与不同的AuthenticationProviders一起使用和API的基本身份验证和Web应用程序的LDAP的分享已经告一段落,感谢您的关注,如果您想了解更多关于org.apache.hadoop.security.authentication.util.SignerSecretProvider的实例源码、org.apache.hadoop.security.authentication.util.ZKSignerSecretProvider的实例源码、org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration.WebMvcAutoConfigurationAdapter的实例源码、org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter的实例源码的相关信息,请在本站查询。
本文标签: