Spring安全过滤器对成功进行身份验证,但发回403响应 [英] Spring security filter authenticates sucessfuly but sends back 403 response
问题描述
我有一个具有以下Web安全配置的Spring Boot应用程序:
I have a spring boot app with the following web security configuration:
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/login**", "/signup**").permitAll()
.and()
.csrf().disable()
.authorizeRequests()
.anyRequest().authenticated()
.and()
.addFilterBefore(jwtAuthenticationFilter,
UsernamePasswordAuthenticationFilter.class);
}
JWTAuthenticationFilter
看起来像这样:
@Component
public class JWTAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
@Autowired
private UserDetailsService customUserDetailsService;
private static Logger logger = LoggerFactory.getLogger(JWTAuthenticationFilter.class);
private final static UrlPathHelper urlPathHelper = new UrlPathHelper();
public JWTAuthenticationFilter() {
super("/greeting");
setAuthenticationManager(new NoOpAuthenticationManager());
}
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
Authentication authentication = AuthenticationService.getAuthentication(request, customUserDetailsService);
return getAuthenticationManager().authenticate(authentication);
}
@Override
protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException {
logger.debug("failed authentication while attempting to access " + urlPathHelper.getPathWithinApplication((HttpServletRequest) request));
}
}
1..身份验证成功完成,我什至在控制台中看到以下日志行:
1. Authentication is done successfuly, I even see the following log line in the console:
2017-05-19 03:11:42 [https-jsse-nio-8443-exec-4] DEBUG c.b.c.s.a.j.JWTAuthenticationFilter -
Authentication success. Updating SecurityContextHolder to contain: org.springframework.security.authentication.UsernamePasswordAuthenticationToken@f297a5c8: Principal: administrator; Credentials: [PROTECTED]; Authenticated: true; Details: null; Granted Authorities: USER_ROLE
但仍然是客户端,收到403响应.
but still the client side, 403 response is recieved.
2..我想使此身份验证筛选器对所有端点执行,但在Web安全配置程序中具有 permitAll
的端点除外.我该怎么办?
2. I want to make this authentication filter execute for all endpoints, except those with permitAll
in the web security configurer. How should I do that?
推荐答案
原因是它正在重定向到 AbstractAuthenticationProcessingFilter
中的默认重定向 URL
,该代码为/
.要覆盖此行为,您需要覆盖 successfulAuthentication()
.
Reason for that is it's redirecting to the default redirect URL
in AbstractAuthenticationProcessingFilter
which is /
. To override this behavior you'll need to override successfulAuthentication()
.
unsuccessfulAuthentication()
方法需要发送身份验证错误.
unsuccessfulAuthentication()
method needs to send an authentication error.
这是这两种方法的实现.
Here's the implementation of both of these methods.
@Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain,
Authentication authResult) throws IOException, ServletException {
SecurityContextHolder.getContext().setAuthentication(authResult);
chain.doFilter(request, response);
}
@Override
protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,
AuthenticationException failed) throws IOException, ServletException {
logger.debug("failed authentication while attempting to access "
+ urlPathHelper.getPathWithinApplication((HttpServletRequest) request));
//Add more descriptive message
response.sendError(HttpServletResponse.SC_UNAUTHORIZED,
"Authentication Failed");
}
以下是一个自包含的工作示例.我已经为所有请求填充了虚拟身份验证对象,您需要使用自己的用户详细信息服务进行验证,然后有条件地填充身份验证对象.
Following is a self contained working example. I have populated dummy authentication object for all requests, you'll need to use your own user details service to validate and then populate authentication object conditionally.
package com.test;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.UrlPathHelper;
@SpringBootApplication
public class TestSpringSecurityCustomApplication {
public static void main(String[] args) {
SpringApplication.run(TestSpringSecurityCustomApplication.class, args);
}
}
@Configuration
class CustomWebSecurity extends WebSecurityConfigurerAdapter {
@Autowired
private JWTAuthenticationFilter jwtAuthenticationFilter;
@Override
protected void configure(HttpSecurity http) throws Exception {
System.out.println("Configuring security");
http.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.authorizeRequests()
.anyRequest().authenticated()
.and().csrf().disable();
}
@Override
public void configure(WebSecurity web)
throws Exception {
web.ignoring().antMatchers("/login/**", "/signup/**");
}
/* Stopping spring from adding filter by default */
@Bean
public FilterRegistrationBean rolesAuthenticationFilterRegistrationDisable(JWTAuthenticationFilter filter) {
FilterRegistrationBean registration = new FilterRegistrationBean(filter);
registration.setEnabled(false);
return registration;
}
}
@RestController
@RequestMapping("greeting")
class TestService {
@RequestMapping("test")
public String test() {
return "Hello World " + new Date();
}
}
@Component
class JWTAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
@Autowired
private UserDetailsService customUserDetailsService;
private static Logger logger = LoggerFactory.getLogger(JWTAuthenticationFilter.class);
private final static UrlPathHelper urlPathHelper = new UrlPathHelper();
public JWTAuthenticationFilter() {
super("/**");
setAuthenticationManager(new NoOpAuthenticationManager());
}
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
throws AuthenticationException, IOException, ServletException {
Authentication authentication = AuthenticationService.getAuthentication(request, customUserDetailsService);
return getAuthenticationManager().authenticate(authentication);
}
@Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain,
Authentication authResult) throws IOException, ServletException {
SecurityContextHolder.getContext().setAuthentication(authResult);
chain.doFilter(request, response);
}
@Override
protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,
AuthenticationException failed) throws IOException, ServletException {
logger.debug("failed authentication while attempting to access "
+ urlPathHelper.getPathWithinApplication((HttpServletRequest) request));
//Add more descriptive message
response.sendError(HttpServletResponse.SC_UNAUTHORIZED,
"Authentication Failed");
}
}
class AuthenticationService {
public static Authentication getAuthentication(HttpServletRequest request, UserDetailsService userDetailsService) {
String username = "TEST_USER";// get this from the token or request
UserDetails user = userDetailsService.loadUserByUsername(username);
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(user,
user.getPassword(), user.getAuthorities());
//Use following to indicate that authentication failed, if user not found or role doesn't match
boolean hasAuthenticationFailed = false;
if(hasAuthenticationFailed) {
throw new AuthenticationException(username){};
}
return authentication;
}
}
@Component
class CustomUserDetailsService implements UserDetailsService {
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
// Returning dummy user, use your own logic for example load from
// database
List<SimpleGrantedAuthority> authorities = Arrays.asList(new SimpleGrantedAuthority(("ROLE_USER")));
User user = new User("TEST_USER", "NO_PASSWORD", authorities);
System.out.println("user : " + user.getUsername());
return user;
}
}
class NoOpAuthenticationManager implements AuthenticationManager {
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
return authentication;
}
}
修改
使用自定义安全过滤器, permitAll()
方法似乎没有任何效果.因此,应在 WebSecurityConfigurerAdapter
中重写以下方法以忽略URL
With custom security filters, permitAll()
method doesn't seem to have any effect. So following method should be overridden in WebSecurityConfigurerAdapter
to ignore URLs
@Override
public void configure(WebSecurity web)
throws Exception {
web.ignoring().antMatchers("/login/**", "/signup/**");
}
注意:我已经修改了上面的代码以使用相同的代码.另外,如果您想忽略要登录 login
的子URL,即.login/dafdsf,则应使用/login/**
而不是/login **
Note: I have modified above code to use the same. Also if you want to ignore sub URLs to login
ie. login/dafdsf, then you should use /login/**
instead of /login**
这篇关于Spring安全过滤器对成功进行身份验证,但发回403响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!