在 Spring Security UsernamePasswordAuthenticationFilter JWT 认证中设置自定义登录 url [英] Set custom login url in Spring Security UsernamePasswordAuthenticationFilter JWT authentication

查看:55
本文介绍了在 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 的 setter,它的目的就是为了做到这一点:

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

这个是那个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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆