本文介绍了如何使用Spring Boot和Spring Security保护REST API?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I know that securing REST API is widely commented topic but I'm not able to create a small prototype that meets my criteria (and I need to confirm that these criteria are realistic). There are so many options how to secure resources and how work with Spring security, I need to clarify if my needs are realistic.

我的要求


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

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

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

  • 所有用户授权后,其他资源都可以访问。

  • 我不知道我不想使用基本身份验证

  • Java代码配置(不是XML)

  • Token based authenticator - users will provide its credentials and get unique and time limited access token. I would like to manage token creation, checking validity, expiration in my own implementation.
  • Some REST resources will be public - no need to authenticate at all,
  • Some resources will be accessible only for users with administrator rights,
  • Other resource will be accessible after authorization for all users.
  • I don't want to use Basic authentication
  • Java code configuration (not XML)

当前状态

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

My REST API works very well, but now I need to secure it. When I was looking for a solution I created a javax.servlet.Filter 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);

    }

但这个解决方案包含 javax。 servlet.filters 无法正常工作,因为使用Spring servlet通过 @ControllerAdvice 进行异常处理时出现问题调度员

But this solution with javax.servlet.filters doesn't work as I need because there is an issue with exception handling via @ControllerAdvice with Spring servlet dispatcher.

我需要什么

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

I would like to know if these criteria are realistic and get any help, how to start securing REST API with Spring Security. I read many tutorials (e.g. Spring Data REST + Spring Security) but all work in very basic configuration - users with their credentials are stored in memory in configuration and I need to work with DBMS and create own authenticator.

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

推荐答案

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

Actually, use Filter for token Auth - best way in this case

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

Eventually, you can create CRUD via Spring Data for managing Token's properties like to expire, etc.

这是我的令牌过滤器:

Here is my token filter:http://pastebin.com/13WWpLq2

和令牌服务实施

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

It's not a problem, you can manage your resources via Spring security config like this: .antMatchers("/rest/blabla/**").permitAll()

查看课程中的 @Secured 注释。示例:

Take a look at @Secured annotation to class. Example:

@Controller
@RequestMapping(value = "/adminservice")
@Secured("ROLE_ADMIN")
public class AdminServiceController {



返回Spring安全配置,您可以像这样配置您的网址:

Back to Spring Security configure, you can configure your url like this:

    http
            .authorizeRequests()
            .antMatchers("/openforall/**").permitAll()
            .antMatchers("/alsoopen/**").permitAll()
            .anyRequest().authenticated()



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

Yep, via token filter, your users will be authenticated.

回到上面的话,看看 @EnableWebSecurity
您的课程将是:

Back to the words above, look at @EnableWebSecurity.Your class will be:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {}

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

You have to override the configure method. Code below, just for example, how to configure matchers. It's from another project.

    @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();
}

这篇关于如何使用Spring Boot和Spring Security保护REST API?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 05:50