Record a pit

In doing spring security JWT login authentication to write a filter

public class JwtAuthenticationTokenFilter extends BasicAuthenticationFilter {

    @Value("${token.header}")
    private String token_header;

    @Autowired
    private UserDetailsServiceImpl userDetailsService;

    @Autowired
    private TokenUtils jwtUtils;

    public JwtAuthenticationTokenFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {

       /* if (request.getMethod().equals(String.valueOf(RequestMethod.GET))) {
            chain.doFilter(request, response);
            return;
        }*/


        String auth_token = request.getHeader(this.token_header);
        final String auth_token_start = "Bearer ";
        if (!StringUtils.isEmpty(auth_token) && auth_token.startsWith(auth_token_start)) {
            auth_token = auth_token.substring(auth_token_start.length());
        } else {
            // 不按规范,不允许通过验证
            = auth_token null ; 

        } 

        String username = jwtUtils.getUsernameFromToken (auth_token); 

        logger.info (String.format ( "Checking authentication for User% S." , username)); 

        // If successful token above parsing and get this username and permissions sessions has not been written 
        IF (username =! null && SecurityContextHolder.getContext () getAuthentication () ==. null ) {
            // the User User = jwtUtils.getUserFromToken (auth_token);
             // with UserDetailsService take from the database to the user's UserDetails class
             // UserDetails class is the entity class Spring Security for storage of user privileges
            UserDetails = UserDetails userDetailsService.loadUserByUsername (username);
             // Check the user brings token is valid
             // include token and userDetails user name is the same, token has expired, token generation time is before the last password change time
             // if examined by 
            IF (jwtUtils.validateToken (auth_token, userDetails and)) {
                 // generated by authentication 
                the UsernamePasswordAuthenticationToken authentication = new new the UsernamePasswordAuthenticationToken (userDetails and, null , userDetails.getAuthorities ()); 
                authentication.setDetails ( new new  WebAuthenticationDetailsSource () buildDetails (Request).) ;
                logger.info (String.format ("Authenticated user %s, setting security context", username));
                // 将权限写入本次会话
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        }
        chain.doFilter(request, response);
    }
}

TokenUtils was injected with userDetailServiceImp not come up empty

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsServiceImpl userDetailsService;

    @Autowired
    private JwtLoginFilter jwtLoginFilter;


    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());
    }



    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/task/**").authenticated()       // 需携带有效 token
              /*  .antMatchers("/admin").hasAuthority("admin")   // 需拥有 admin 这个权限
                .antMatchers("/ADMIN").hasRole("ADMIN") // need to have this identity ADMIN* /
                .anyRequest (). permitAll () 
                .AND () 
                .csrf () 
                .disable ()                       // disable Spring Security comes with cross-domain processing 
                .sessionManagement ()                         // customize our own strategy session 
                .sessionCreationPolicy (SessionCreationPolicy.STATELESS) // adjusted to make Spring Security does not create and use the session 
.AND ()
.addFilter (new new JwtLoginFilter (
authenticationManagerBean () ))
.addFilter (new new JwtAuthenticationTokenFilter ( authenticationManagerBean () ));


}

In websecurityconfig here addfFilter was a direct new objects into them, but it was not because it is a new subject in the spring container, so the injection does not go.

@Autowired inject Spring Bean, the current class must also Spring Bean can call it, can not use new xxx () to get the object, the object obtained in this way can not be called @Autowired injected Bean.

Later @bean direct use or direct way to add annotations @component custom filter is added to the spring container can be friends!

Guess you like

Origin www.cnblogs.com/yyZNL/p/11576058.html