我正在尝试通过Java Config配置Spring Security来处理我的应用程序上的两种身份验证:基于表单的(用户登录)和基于令牌的(REST api)。
表单配置很简单,除了我必须创建自己的SecuritySocialConfigurer
(基本上是SpringSocialConfigurer
的一个副本,带有一个自定义的身份验证成功处理程序,该处理程序生成一个JWT令牌并在响应中使用它设置一个cookie )。
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
super.configure(auth);
auth
.userDetailsService(userDetailsService())
.passwordEncoder(NoOpPasswordEncoder.getInstance());
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/css/**", "/img/**");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.formLogin()
.loginPage("/signin")
.loginProcessingUrl("/signin/authenticate")
.failureUrl("/signin?param.error=bad_credentials")
.and()
.logout()
.logoutUrl("/signout")
.deleteCookies("JSESSIONID")
.and()
.authorizeRequests()
.antMatchers("/admin/**", "favicon.ico", "/public/**", "/auth/**", "/signin/**").permitAll()
.antMatchers("/**").hasRole("USER")
.and()
.rememberMe()
.and()
.apply(new MilesSocialSecurityConfigurer());
}
只有在使用此配置时,我才能访问http://localhost:8080
并被重定向至http://localhost:8080/signin
以执行登录。成功登录后,我检查JWT令牌cookie是否存在。
第二个安全配置目的是在调用REST api时检查JWT令牌是否存在。
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.addFilterAfter(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
.antMatcher("/api/**")
.csrf()
.disable()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.exceptionHandling()
.authenticationEntryPoint(restAuthenticationEntryPoint)
.and()
.authorizeRequests()
.antMatchers("favicon.ico", "/public/**", "/auth/**", "/signin/**").permitAll()
.antMatchers("/**").authenticated()
;
}
@Bean
public JwtAuthenticationFilter jwtAuthenticationFilter() throws Exception {
JwtAuthenticationFilter filter = new JwtAuthenticationFilter("/api/**");
filter.setAuthenticationSuccessHandler(jwtAuthenticationSuccessHandler);
filter.setAuthenticationManager(apiAuthenticationManager());
return filter;
}
@Bean
public ProviderManager apiAuthenticationManager() {
return new ProviderManager(Arrays.asList(jwtAuthenticationProvider));
}
JwtAuthenticationProvider
是一个类,它解析JWT令牌并生成UserDetails
对象,或者在令牌不存在或无效时抛出AuthenticationException
。
当第二个配置就绪时,我无法导航到http://localhost:8080
(或/signin
)来启动登录过程-浏览器返回一个ERR_TOO_MANY_REDIRECTS。
我尝试了一些东西,但没有任何成功。任何关于正在发生的事情的线索都将不胜感激。
谢谢。
发布于 2016-03-06 14:22:41
变化
.antMatchers("/**").authenticated()
至
.anyRequest().authenticated()
这意味着任何与您显式定义的URL不匹配的URL都将需要身份验证。
https://stackoverflow.com/questions/35805055
复制相似问题