【发布时间】:2017-01-02 15:19:51
【问题描述】:
我在我的应用程序上使用带有 spring:boot 的 jwt 身份验证。一切顺利。如果标头中存在有效令牌,则它正在得到验证并且响应发送正常。
但是如何将无效请求重定向到登录页面,并在成功登录后将它们重定向回最初请求的页面。
这是我的配置方法
httpSecurity
.csrf().disable().exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.authorizeRequests()
.antMatchers(HttpMethod.GET, "/", "/*.html", "/favicon.ico", "/**/*.html", "/**/*.css", "/**/*.js")
.permitAll().antMatchers("/auth/**").permitAll().anyRequest().authenticated();
httpSecurity.addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class);
httpSecurity.headers().cacheControl();
这是我的身份验证过滤器
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
String authToken = httpRequest.getHeader(this.tokenHeader);
// authToken.startsWith("Bearer ")
// String authToken = header.substring(7);
String username = jwtTokenUtil.getUsernameFromToken(authToken);
System.out.println("Token is " + authToken);
System.out.println("Username is " + username);
System.out.println("Audience is from " + jwtTokenUtil.getAudienceFromToken(authToken));
if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
System.out.println(userDetails.getAuthorities());
if (jwtTokenUtil.validateToken(authToken, userDetails)) {
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
userDetails, null, userDetails.getAuthorities());
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpRequest));
SecurityContextHolder.getContext().setAuthentication(authentication);
} else {
System.out.println("Token is invalid ");
}
}
chain.doFilter(request, response);
}
}
【问题讨论】:
标签: spring spring-mvc spring-security jwt