'How to change Login URL in Spring Security
I created an API that provides User authentication and it's login operation is handled on default '/login' path by Spring Security.
I want to change this path to 'api/v1/login'.
this is my security config :
http.cors().and().csrf().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/h2-console/**/**").permitAll()
.antMatchers(HttpMethod.POST,"/user/register").permitAll()
.antMatchers("/user/activate").permitAll()
.antMatchers("/user/reset-password").permitAll()
.antMatchers("/user/reset-password").permitAll()
.antMatchers("/admin/user").hasRole("ADMIN")
.antMatchers("/roles").permitAll()
.antMatchers("/user/**").hasRole("USER")
.and()
.formLogin().loginProcessingUrl("/api/v1/login")
.and()
.exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint)
.and()
.addFilterBefore(new ExceptionHandlerFilter(), UsernamePasswordAuthenticationFilter.class)
.addFilter(new JwtAuthenticationFilter(authenticationManager()))
.addFilter(new JwtAuthorizationFilter(authenticationManager(), jwtUserDetailService));
I have added this line to change it :
.formLogin().loginProcessingUrl("/api/v1/login")
But it is still working under '/login' path.
"/api/v1/login" return 404.
Is there any way to change it ?
Spring Boot Version : 2.0.0.RELEASE
Solution 1:[1]
You are extending org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter which itself extendsorg.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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | kakabali |
