在 Spring Security UsernamePasswordAuthenticationFilter JWT 身

时间:2023-01-13
本文介绍了在 Spring Security UsernamePasswordAuthenticationFilter JWT 身份验证中设置自定义登录 url的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在关注 此 auth0 的教程 以确保我的应用程序使用 JWT.

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

我最终得到了以下 WebSecurity 配置:

I've ended up with the following WebSecurity configuration:

@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:

and the following 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);
    }
}

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

At the moment, the app accepts POST requests on the /login URL. I wonder how to change the URL to, let's say, /api/auth/login. Is there any way to inject the URL string into the authentication filter or to set it somehow in the security config?

推荐答案

你正在扩展 org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter 本身扩展org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.在这最后一个类中,有一个名为 setFilterProcessesUrl 的设置器,它的目的就是这样做:

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)

public void setFilterProcessesUrl(String filterProcessesUrl)

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

Sets the URL that determines if authentication is required

参数:filterProcessesUrl

Parameters: filterProcessesUrl

This 是指向该 javadoc 部分的链接

This is the link to that javadoc section

所以在你的 WebSecurityConfigurerAdapter 你可以这样做:

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;
}

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

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

.addFilter(getJWTAuthenticationFilter())

这篇关于在 Spring Security UsernamePasswordAuthenticationFilter JWT 身份验证中设置自定义登录 url的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!

上一篇:访问资源服务器控制器内的 Spring OAuth 2 JWT 有效负 下一篇:JWT 发出相同的令牌

相关文章

最新文章