我做了使用Spring Security的弹簧页。当我尝试访问此网页内的任何链接,如果会议没有设置,将您重定向到登录页面:/登录。这是好的,但现在我做了这个网站里面一个简单的HTTP REST API。我想如果我试图访问内部的任何URL / API / **只下降了401,而不是发送一个HTTP重定向登录。
我已经做了筛选与preHandle:
公共类BusinessKeyInterceptor扩展HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth != null && auth.isAuthenticated()
&&
// when Anonymous Authentication is enabled
!(auth instanceof AnonymousAuthenticationToken)) {
// other stuf ....
}
} else {
if (request.getRequestURI().startsWith("/api")) {
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
return false;
}
}
return true;
}
}
但在这种情况下,请求URI已经是/登录
我的配置:
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.anyRequest().authenticated()
.and().sessionManagement()
.invalidSessionUrl("/login?invalid")
.and().csrf().disable().formLogin()
.loginPage("/login")
.failureHandler(customAuthenticationFailureHandler)
.defaultSuccessUrl("/loggedIn")
.usernameParameter("email")
.passwordParameter("password")
.successHandler(authenticationSuccessHandler)
.and().logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/").and().exceptionHandling()
.accessDeniedPage("/access-denied")
;
}
我建议不会与新的REST API配置混合以前的安全配置。你可以做到以下几点:
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Configuration
@Order(1)
public static class WebConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.antMatchers("/web")
...
/* Your previous config would go here */
}
}
@Configuration
@Order(2)
public static class ApiConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.antMatchers("/web")
... /* Your /api configuration goes here */
.exceptionHandling()
.authenticationEntryPoint(customAuthenticationEntryPoint)
}
@Bean
AuthenticationEntryPoint customAuthenticationEntryPoint() {
return new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED);
}
}
}
通过这种方式,你可以单独配置您的REST API。现在你可以有不同的为你的REST API认证一个切入点。事实是,你很可能会想也提供了自定义的故障处理程序,并成功处理程序,你现在可以做容易,并且仍将从您的Web应用程序的其余部分分开。