[英]Changing the login service URL in spring security
嗨,我已經使用 JWT 過濾器在我的 Spring Boot Web 應用程序中實現了 Spring 安全性。 但是默認身份驗證發生在 url http://localhost:8080/login
。 如何將/login
更改為我需要的某些 url,例如/rest/auth/login
?
我的網絡WebSecurity
類是
@EnableWebSecurity
public class WebSecurity extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Autowired
private BCryptPasswordEncoder bCryptPasswordEncoder;
public WebSecurity( UserDetailsService userDetailsService, BCryptPasswordEncoder bCryptPasswordEncoder )
{
this.userDetailsService = userDetailsService;
this.bCryptPasswordEncoder = bCryptPasswordEncoder;
}
@Override
protected void configure( HttpSecurity http ) throws Exception
{
http.cors().and().csrf().disable().authorizeRequests().antMatchers(HttpMethod.POST, "/rest/auth/**").permitAll()
.antMatchers("/static/*").permitAll().antMatchers("/").permitAll()
/* .anyRequest().authenticated() */.and()
.addFilter(new JWTAuthenticationFilter(authenticationManager()))
.addFilter(new JWTAuthorizationFilter(authenticationManager()));
}
@Override
public void configure( AuthenticationManagerBuilder auth ) throws Exception
{
auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder);
}
@Override
public void configure( org.springframework.security.config.annotation.web.builders.WebSecurity web )
throws Exception
{
web.ignoring().antMatchers("/static/**");
}
@Bean
CorsConfigurationSource corsConfigurationSource()
{
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", new CorsConfiguration().applyPermitDefaultValues());
return source;
}
}
我的靜態目錄下的資源文件夾中有一個登錄頁面。 Spring security 的工作方式是,當用戶從表單發送userName
和password
,客戶端必須將這些憑據發送到服務器中的/login
路徑,以便 spring security 驗證這些憑據並創建令牌。 但我想將默認路徑/login
更改為/rest/auth/login
您需要調整WebSecurityConfig.java
和JWTAuthenticationFilter
。
@Override
protected void configure( HttpSecurity http ) throws Exception
{
http.csrf().disable()
.authorizeRequests()
.antMatchers("/rest/noauth/**").permitAll()
.antMatchers("/rest/login").permitAll()
.antMatchers("/rest/logout").permitAll()
.antMatchers("/src/**").permitAll()
.antMatchers("/v2/api-docs/**", "/configuration/ui/**", "/swagger-resources/**",
"/configuration/security/**", "/swagger-ui.html/**", "/webjars/**")
.permitAll()
.anyRequest().authenticated()
.and()
.logout().addLogoutHandler(logoutHandler).logoutSuccessHandler(logoutSuccessHandler)
.logoutUrl("/rest/logout")
.and()
.addFilterBefore(
new JWTAuthenticationFilter("/rest/login",
UsernamePasswordAuthenticationFilter.class)
.addFilterBefore(new JWTAuthorizationFilter(authenticationManager(), authTokenModelRepository),
UsernamePasswordAuthenticationFilter.class);
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
並使您的JWTAuthenticationFilter
擴展AbstractAuthenticationProcessingFilter
,它具有一個采用filterProcessingURl
的構造函數,我將/rest/login
作為參數傳遞。
public class JWTAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
private static final Logger LOGGER = LoggerFactory.getLogger(JWTAuthenticationFilter.class);
private AuthenticationManager authenticationManager;
private TokenService tokenService;
private UserModel credentials;
private RefreshTokenService refreshTokenService;
private AuthTokenModelRepository authTokenModelRepository;
private UserModelRepository userModelRepository;
public JWTAuthenticationFilter( String loginUrl, AuthenticationManager authenticationManager,
TokenService tokenService, RefreshTokenService refreshTokenService,
AuthTokenModelRepository authTokenModelRepository, UserModelRepository userModelRepository )
{
super(new AntPathRequestMatcher(loginUrl));
}
完成上述配置后,將針對請求/rest/login
執行JWTAuthenticationFilter
。
在您的 AuthenticationFilter 中,您可以在構造過程中調用setFilterProcessesUrl ,例如:
public class JWTAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
private AuthenticationManager authenticationManager;
public JWTAuthenticationFilter(AuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
setFilterProcessesUrl("/api/v1/tokens"); // <--- like this
}
...
希望它有幫助。
只是為了補充Jordy Baylac 的回答:在 Kotlin 中,一旦我通過主構造函數注入依賴項,我就很難設置過濾器。 我的解決方案是做這樣的事情:
class AuthenticationFilter(
authenticationManager: AuthenticationManager?,
private var jwtUtilsComponent: JwtUtilsComponent,
) : UsernamePasswordAuthenticationFilter() {
private val authManager: AuthenticationManager? = authenticationManager
init {
setFilterProcessesUrl("/${ApiProperties.BASE_PATH}/login")
}
// more code
}
然后它工作得很好。
在 configure 方法中嘗試添加loginProcessungUrl()
方法。 您可以在參數中設置值
.addFilter(new JWTAuthorizationFilter(authenticationManager()))
.loginProcessingUrl(LOGIN_URL);
您需要提供登錄頁面的 url 和將處理身份驗證的 url。 這可以通過像這樣覆蓋方法來完成:
@Override
protected void configure( HttpSecurity http ) throws Exception
{
http.cors().and().csrf().disable().
authorizeRequests().
antMatchers(HttpMethod.POST, "/rest/auth/**").
permitAll()
.antMatchers("/static/*").permitAll()
.antMatchers("/").permitAll()
.and().formLogin().
/*This is where the juice is*/
loginPage("/login").loginProcessingUrl("/rest/auth/login")
/* .anyRequest().authenticated() */.and()
.addFilter(new JWTAuthenticationFilter(authenticationManager()))
.addFilter(new JWTAuthorizationFilter(authenticationManager()));
}
loginPage("/login") 可以替換為靜態登錄頁面的路由,而 loginProcessingUrl 是處理登錄邏輯的控制器的 URL。 確保 /login 和 /loginProcesingUrl 都存在控制器。
修改“HttpSecurity”,如下,示例:
@Override
protected void configure( HttpSecurity http ) throws Exception {
http.cors().and().csrf().disable().authorizeRequests().antMatchers(HttpMethod.POST, "/rest/auth/**").permitAll()
.antMatchers("/static/*").permitAll().antMatchers("/").permitAll()
/* .anyRequest().authenticated() */
.and()
.formLogin()
.loginPage("/login")
.loginProcessingUrl("/rest/auth/login")
.permitAll()
.and()
.logout()
.permitAll();
.and()
.addFilter(new JWTAuthenticationFilter(authenticationManager()))
.addFilter(new JWTAuthorizationFilter(authenticationManager()));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.