Set custom login url in Spring Security UsernamePasswordAuthenticationFilter JWT authentication

前端 未结 2 1691
Happy的楠姐
Happy的楠姐 2020-12-29 14:38

I\'m following this auth0\'s tutorial to secure my application using JWT.

I\'ve ended up with the following WebSecurity configuration:

@EnableWebSecu         


        
相关标签:
2条回答
  • 2020-12-29 14:44

    You are extending org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter which itself extends org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter. In this last class, there is a setter called setFilterProcessesUrl which is intended to do just this:

    setFilterProcessesUrl

    public void setFilterProcessesUrl(String filterProcessesUrl)

    Sets the URL that determines if authentication is required

    Parameters: filterProcessesUrl

    This is the link to that javadoc section

    So in your WebSecurityConfigurerAdapter you could do just like this:

    @Bean
    public JWTAuthenticationFilter getJWTAuthenticationFilter() {
        final JWTAuthenticationFilter filter = new JWTAuthenticationFilter(authenticationManager());
        filter.setFilterProcessesUrl("/api/auth/login");
        return filter;
    }
    

    And then in your configure method in the same class just reference it instead of creating new instance:

    .addFilter(getJWTAuthenticationFilter())
    
    0 讨论(0)
  • 2020-12-29 14:53

    A little improvement could be to just create your filter with custom process url and use it without create a bean that I think you don't need anywhere else than here.

    JWTAuthenticationFilter authenticationFilter = new JWTAuthenticationFilter(authenticationManager());
    authenticationFilter.setFilterProcessesUrl("/mobile/login");
    ....
    .and()
    .addFilter(authenticationFilter)
    .addFilter(new JWTAuthenticationFilter(authenticationManager()))
    
    0 讨论(0)
提交回复
热议问题