一尘不染

在Spring Security UsernamePasswordAuthenticationFilter JWT身份验证中设置自定义登录URL

java

我正在按照auth0的教程使用JWT保护我的应用程序。

我完成了以下WebSecurity配置:

@EnableWebSecurity
@AllArgsConstructor(onConstructor = @__(@Autowired))
public class WebSecurity extends WebSecurityConfigurerAdapter {

    private final UserDetailsService userDetailsService;
    private final BCryptPasswordEncoder passwordEncoder;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin()
                .and().cors()
                .and().csrf()
                .disable()
                .authorizeRequests()
                .antMatchers(HttpMethod.POST, REGISTER_URL).permitAll()
                .antMatchers(HttpMethod.POST, LOGIN_URL).permitAll()
                .anyRequest().authenticated()
                .and()
                .addFilter(new JWTAuthorizationFilter(authenticationManager()))
                .addFilter(new JWTAuthenticationFilter(authenticationManager()))
                // This disables session creation on Spring Security
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }

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

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", new CorsConfiguration().applyPermitDefaultValues());
        return source;
    }

}

和以下JWTAuthenticationFilter:

public class JWTAuthenticationFilter extends UsernamePasswordAuthenticationFilter {

    private final AuthenticationManager authenticationManager;

    public JWTAuthenticationFilter(AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        try {
            ApplicationUser credentials = new ObjectMapper().readValue(request.getInputStream(), ApplicationUser.class);
            return authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(
                            credentials.getUsername(),
                            credentials.getPassword(),
                            new ArrayList<>()
                    )
            );
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
        String token = Jwts.builder()
                .setSubject(((User) authResult.getPrincipal()).getUsername())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
                .signWith(SignatureAlgorithm.HS512, SECRET.getBytes())
                .compact();
        response.addHeader(HEADER_STRING, TOKEN_PREFIX + token);
    }
}

目前,该应用接受/loginURL
上的POST请求。我想知道如何将URL更改为/api/auth/login。有什么方法可以将URL字符串注入到身份验证过滤器中,或以某种方式在安全配置中对其进行设置?


阅读 730

收藏
2020-12-03

共1个答案

一尘不染

您正在扩展org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter,它本身又扩展了
org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter。在最后一节课中,有一个名为setter的操作setFilterProcessesUrl,它旨在执行以下操作:

setFilterProcessesUrl

public void setFilterProcessesUrl (字符串filterProcessesUrl)

设置确定是否需要身份验证的URL

参数:filterProcessesUrl

是该javadoc部分的链接

因此,您WebSecurityConfigurerAdapter可以像这样:

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

然后在configure同一个类的方法中,只需引用它即可,而不是创建新实例:

.addFilter(getJWTAuthenticationFilter())
2020-12-03