在spring security中更改登录服务URL

时间:2017-09-01 09:04:19

标签: java spring spring-boot spring-security

您好我在使用JWT过滤器的Spring启动Web应用程序中实现了Spring安全性。但默认身份验证发生在网址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;
}
}

我在static目录下的资源文件夹中有一个登录页面。 Spring安全性的工作方式是,当用户从表单发送userNamepassword时,客户端必须将这些凭据发送到服务器中的/login路径,以便spring安全性验证这些凭据和创建令牌。但我想将默认路径/login更改为/rest/auth/login

5 个答案:

答案 0 :(得分:5)

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

public class JWTAuthenticationFilter extends UsernamePasswordAuthenticationFilter {

   private AuthenticationManager authenticationManager;

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

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

   ...

希望有帮助。

答案 1 :(得分:4)

您需要调整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);

}

并使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));

}

完成上述配置后,将为请求JWTAuthenticationFilter执行/rest/login

答案 2 :(得分:0)

您需要提供登录页面的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(&#34; / login&#34;)可以替换为静态登录页面的路径,而loginProcessingUrl是处理登录逻辑的控制器的URL。确保/ login和/ loginProcesingUrl都存在控制器。

答案 3 :(得分:-1)

在configure方法中尝试添加loginProcessungUrl()方法。您可以在参数

中设置值
.addFilter(new JWTAuthorizationFilter(authenticationManager()))
.loginProcessingUrl(LOGIN_URL);

答案 4 :(得分:-1)

修改“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()));
}