我试图通过Java配置来处理两种身份验证:基于表单(基于用户登录)和基于令牌(REST api)的两种身份验证。多个Web安全性导致ERR_TOO_MANY_REDIRECTS
的形式配置是简单明了,除非我不得不创建我自己的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。
我尝试了一些没有成功的事情。任何关于正在发生的事情的线索将不胜感激。
谢谢。
不幸的是,没有解决问题。尝试访问任何应用网址时,我仍然有ERR_TOO_MANY_REDIRECTS。 –