我正在为移动应用程序构建REST服务(JAVA / SPRING),其中必须处理身份验证和授权。对于身份验证,我使用的是外部工具,但对于基于角色的授权,我想使用Spring Security。该项目使用 Spring Boot + Spring Data JPA + Spring REST 。
我做了一个示例项目以获得Spring Security的一些实际操作,但是花了几个小时后我能够让它工作一些,但有特别的疑问。
Sample的几个类: -
@Configuration
@EnableWebSecurity
@ComponentScan("com.ezetap.security")
@EnableGlobalMethodSecurity(prePostEnabled = true,securedEnabled=true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired DataSource dataSource;
@Autowired CustomAuthenticationProvider authenticationProvider;
@Autowired CustomerUserDetailService customerUserDetailService;//Overrides loadByUserName method
@Autowired
public void configure(AuthenticationManagerBuilder auth) throws Exception {
//auth.userDetailsService(customerUserDetailService);
auth.authenticationProvider(authenticationProvider);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers(HttpMethod.GET,"/spring-security/test/**").hasRole("USER");
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().csrf().disable();
http.addFilterBefore(new RestAuthenticationFilter(authenticationProvider,customerUserDetailService), BasicAuthenticationFilter.class);
}
}
public class RestAuthenticationFilter extends GenericFilterBean {
CustomerUserDetailService authenticationService;
AuthenticationProvider authenticationProvider;
public RestAuthenticationFilter() {
}
public RestAuthenticationFilter(CustomerUserDetailService customerUserDetailService) {
this.authenticationService=customerUserDetailService;
}
public RestAuthenticationFilter(AuthenticationProvider authenticationProvider,
CustomerUserDetailService customerUserDetailService) {
this.authenticationProvider=authenticationProvider;
this.authenticationService=customerUserDetailService;
}
public final String HEADER_SECURITY_TOKEN = "X-CustomToken";
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
if("test".equalsIgnoreCase(request.getHeader(HEADER_SECURITY_TOKEN))){
UserDetails userDetails=authenticationService.loadUserByUsername("");//assume this is working
UsernamePasswordAuthenticationToken authentication =
new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authentication);
chain.doFilter(request, response);
}else{
response.sendError(401, "Authorization failed");
//response.getWriter().append("Access denied");
}
} <br>