Set custom login url in Spring Security UsernamePasswordAuthenticationFilter JWT authentication(在 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Spring Security UsernamePasswordAuthenticationFilter JWT 身
基础教程推荐
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- Java Swing计时器未清除 2022-01-01
- 从 python 访问 JVM 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- 多个组件的复杂布局 2022-01-01
- 大摇大摆的枚举 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
