私はSpring Securityを使用するアプリケーションを作成します。私はTokenFilterとWebSecurityConfigを書きました。 私の質問は、SecurityContextにログに記録されたユーザーがどのくらいの期間含まれていますか? 次の質問:私のセキュリティ設定セッションはステートレスかノーですか? SessionのSecurityContext置換えですか?REST - セッションの作成
私のアプリケーションはステートレスな原則を満たしていますか?
public class TokenFilter extends OncePerRequestFilter {
@Autowired
private UserDetailsService userDetailsService;
@Autowired
private TokenHelper tokenHelper;
private String tokenHeader = "Auth";
@Override
protected void doFilterInternal(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse,
FilterChain filterChain) throws ServletException, IOException {
final String authToken = httpServletRequest.getHeader(this.tokenHeader);
final String username = tokenHelper.getUsernameFromToken(authToken);
if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
final UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
if (tokenHelper.validateToken(authToken, userDetails)) {
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
userDetails,
null,
userDetails.getAuthorities()
);
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpServletRequest));
SecurityContextHolder.getContext().setAuthentication(authentication);
}
}
filterChain.doFilter(httpServletRequest, httpServletResponse);
}
}
とセキュリティの設定:
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UnauthorizedHandler unauthorizedHandler;
@Autowired
private UserDetailsService userDetailsService;
@Autowired
public void configureAuthentication(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
authenticationManagerBuilder
.userDetailsService(this.userDetailsService)
.passwordEncoder(this.passwordEncoder);
}
@Autowired
public BCryptPasswordEncoder passwordEncoder;
@Autowired
public TokenFilter tokenFilter;
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity
.csrf().disable()
.exceptionHandling().authenticationEntryPoint(unauthorizedHandler)
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers(HttpMethod.POST, "/login").permitAll()
.anyRequest().authenticated();
httpSecurity.addFilterBefore(
tokenFilter,
UsernamePasswordAuthenticationFilter.class
);
httpSecurity.headers().cacheControl();
}
}