更改spring security中的登录服务URL

Vir*_*rat 5 java spring spring-security spring-boot

嗨,我已经使用 JWT 过滤器在我的 Spring Boot Web 应用程序中实现了 Spring 安全性。但默认身份验证发生在 url http://localhost:8080/login。如何更改/login为我需要的一些网址/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;
}
}
Run Code Online (Sandbox Code Playgroud)

我的静态目录下的资源文件夹中有一个登录页面。春季安全工作的方式是,当用户发送userNamepassword从形式,客户端发送这些凭据/login路径在服务器上,让春天的安全验证这些凭据,并创建令牌。但我想将该默认路径更改/login/rest/auth/login

San*_*a J 7

您需要调整WebSecurityConfig.javaJWTAuthenticationFilter

@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);

}
Run Code Online (Sandbox Code Playgroud)

并使您的JWTAuthenticationFilter扩展AbstractAuthenticationProcessingFilter具有一个构造函数,该构造函数将filterProcessingURl和 I/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));

}
Run Code Online (Sandbox Code Playgroud)

上面的配置完成后,JWTAuthenticationFilter就会对请求执行/rest/login


Jor*_*lac 6

在您的 AuthenticationFilter 中,您可以在构造过程中调用setFilterProcessesUrl,例如:

public class JWTAuthenticationFilter extends UsernamePasswordAuthenticationFilter {

   private AuthenticationManager authenticationManager;

   public JWTAuthenticationFilter(AuthenticationManager authenticationManager) {
      this.authenticationManager = authenticationManager;

      setFilterProcessesUrl("/api/v1/tokens"); // <--- like this
   }

   ...
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你。

  • 这是可行的,并且是比所选答案更简单的方法。 (2认同)