2017-07-11 34 views
0

这是我的webapp如何避免使用Spring Security重定向到某个URL的登录表单?

@Override 
protected void configure(HttpSecurity http) throws Exception { 
    http 
     .authorizeRequests() 
      .antMatchers("/", LOGIN, "/webjars/**").permitAll() 
      .antMatchers(CONFIGURATION).hasAuthority(Authorities.AUTHORITY_SOLMAN72_EXPORT_ENABLED.getKey()) 
      .antMatchers("/api/**").hasAuthority(Authorities.AUTHORITY_SOLMAN72_EXPORT_ENABLED.getKey()) 
      .and() 
     .formLogin() 
      .loginPage(LOGIN) 
      .and() 
     .addFilterBefore(oAuth2ClientAuthenticationProcessingFilter, BasicAuthenticationFilter.class); 
} 

目前服务器重定向到LOGIN页面不具有正确的凭证每个请求的春季安全配置。

我想重定向到LOGIN页面只有授权请求CONFIGURATION,而到/api/**未经授权的请求应与403

什么是实现这一目标的一个很好的方式回答?

回答

1

你可以使用DelegatingAuthenticationEntryPoint

AuthenticationEntryPoint它选择根据RequestMatcher评价的具体AuthenticationEntryPoint

Http403ForbiddenEntryPoint对于/api/**LoginUrlAuthenticationEntryPoint作为默认入口点。

@Bean 
public DelegatingAuthenticationEntryPoint delegatingAuthenticationEntryPoint() { 
    LinkedHashMap<RequestMatcher, AuthenticationEntryPoint> entryPoints = new LinkedHashMap<RequestMatcher, AuthenticationEntryPoint>(); 
    entryPoints.put(new AntPathRequestMatcher("/api/**"), new Http403ForbiddenEntryPoint()); 
    DelegatingAuthenticationEntryPoint defaultEntryPoint = new DelegatingAuthenticationEntryPoint(entryPoints); 
    defaultEntryPoint.setDefaultEntryPoint(new LoginUrlAuthenticationEntryPoint(LOGIN)); 
    return defaultEntryPoint; 
} 
1

我使用AuthenticationEntryPoint解决我的问题:

http 
    .authorizeRequests() 
     .antMatchers(LOGIN).permitAll() 
     .antMatchers("/**").hasAuthority(Authorities.AUTHORITY_SOLMAN72_EXPORT_ENABLED.getKey()) 
     .and() 
    .addFilterBefore(oAuth2ClientAuthenticationProcessingFilter, BasicAuthenticationFilter.class) 
    .exceptionHandling().authenticationEntryPoint(unauthenticatedRequestHandler); 
@Bean 
UnauthenticatedRequestHandler unauthenticatedRequestHandler() { 
    return new UnauthenticatedRequestHandler(); 
} 

static class UnauthenticatedRequestHandler implements AuthenticationEntryPoint { 

    @Override 
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException { 
     if (request.getServletPath().startsWith("/api/")) { 
      response.setStatus(403); 
     } else { 
      response.sendRedirect(LOGIN); 
     } 
    } 
} 
相关问题