如何使用Spring Boot和Spring Security保护REST API?

Art*_*gon 74 java rest spring spring-security

我知道保护REST API是一个广泛评论的主题,但我无法创建符合我的标准的小型原型(我需要确认这些标准是现实的).如何保护资源以及如何使用Spring安全性有很多选择,我需要澄清我的需求是否切合实际.

我的要求

  • 基于令牌的身份验证器 - 用户将提供其凭据并获得唯一且受时间限制的访问令牌.我想管理令牌创建,检查有效性,在我自己的实现中过期.
  • 一些REST资源将是公开的 - 根本不需要进行身份验证,
  • 只有具有管理员权限的用户才能访问某些资源,
  • 在授权所有用户后,可以访问其他资源.
  • 我不想使用基本身份验证
  • Java代码配置(不是XML)

当前状态

我的REST API运行良好,但现在我需要保护它.当我在寻找解决方案时,我创建了一个javax.servlet.Filter过滤器:

  @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) req;

        String accessToken = request.getHeader(AUTHORIZATION_TOKEN);
        Account account = accountDao.find(accessToken);

        if (account == null) {    
            throw new UnauthorizedException();    
        }

        chain.doFilter(req, res);

    }
Run Code Online (Sandbox Code Playgroud)

但是这个解决方案javax.servlet.filters不能正常工作,因为@ControllerAdviceSpring 存在异常处理问题servlet dispatcher.

我需要的

我想知道这些标准是否切合实际并获得任何帮助,如何开始使用Spring Security保护REST API.我阅读了许多教程(例如Spring Data REST + Spring Security),但都在非常基本的配置中工作 - 具有凭据的用户在配置中存储在内存中,我需要使用DBMS并创建自己的身份验证器.

请给我一些如何开始的想法.

Ole*_*kin 61

基于令牌的身份验证 - 用户将提供其凭据并获得唯一且受时间限制的访问令牌.我想管理令牌创建,检查有效性,在我自己的实现中过期.

实际上,使用Filter for token Auth - 在这种情况下最好的方法

最后,您可以通过Spring Data创建CRUD来管理Token的属性,例如过期等.

这是我的令牌过滤器:http: //pastebin.com/13WWpLq2

和令牌服务实现

http://pastebin.com/dUYM555E

一些REST资源将是公共的 - 根本不需要进行身份验证

这不是问题,您可以通过Spring安全配置管理您的资源,如下所示: .antMatchers("/rest/blabla/**").permitAll()

只有具有管理员权限的用户才能访问某些资源,

看一下@Secured注释到课堂.例:

@Controller
@RequestMapping(value = "/adminservice")
@Secured("ROLE_ADMIN")
public class AdminServiceController {
Run Code Online (Sandbox Code Playgroud)

在授权所有用户后,可以访问其他资源.

回到Spring安全配置,您可以像这样配置您的URL:

    http
            .authorizeRequests()
            .antMatchers("/openforall/**").permitAll()
            .antMatchers("/alsoopen/**").permitAll()
            .anyRequest().authenticated()
Run Code Online (Sandbox Code Playgroud)

我不想使用基本身份验证

是的,通过令牌过滤器,您的用户将被验证.

Java代码配置(不是XML)

回到上面的话,看看@EnableWebSecurity.你的课将是:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {}
Run Code Online (Sandbox Code Playgroud)

您必须覆盖configure方法.下面的代码,例如,如何配置匹配器.它来自另一个项目.

    @Override
protected void configure(HttpSecurity http) throws Exception {
    http
            .authorizeRequests()
            .antMatchers("/assets/**").permitAll()
            .anyRequest().authenticated()
            .and()
            .formLogin()
                .usernameParameter("j_username")
                .passwordParameter("j_password")
                .loginPage("/login")
                .defaultSuccessUrl("/", true)
                .successHandler(customAuthenticationSuccessHandler)
                .permitAll()
            .and()
                .logout()
                .logoutUrl("/logout")
                .invalidateHttpSession(true)
                .logoutSuccessUrl("/")
                .deleteCookies("JSESSIONID")
                .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
            .and()
                .csrf();
}
Run Code Online (Sandbox Code Playgroud)

  • 是否有包含所有要求的示例项目? (2认同)