首页 文章

Spring Security - 基于令牌的API身份验证和用户/密码身份验证

提问于
浏览
43

我正在尝试创建一个主要使用Spring提供REST API的webapp,并且我正在尝试配置安全端 .

我正在尝试实现这种模式:https://developers.google.com/accounts/docs/MobileApps(谷歌已完全更改了该页面,因此不再有意义 - 请参阅我在此处引用的页面:http://web.archive.org/web/20130822184827/https://developers.google.com/accounts/docs/MobileApps

这是我需要做的事情:

  • Web应用程序具有简单的登录/注册表单,可以使用普通的spring用户/密码身份验证(之前使用dao / authenticationmanager / userdetailsservice等完成了此类事情)

  • REST api endpoints 是无状态会话,并且每个请求都基于请求提供的令牌进行身份验证

(例如,用户使用普通表单登录/注册,webapp提供带有令牌的安全cookie,然后可以在以下API请求中使用)

我有一个正常的身份验证设置如下:

@Override protected void configure(HttpSecurity http) throws Exception {
    http
        .csrf()
            .disable()
        .authorizeRequests()
            .antMatchers("/resources/**").permitAll()
            .antMatchers("/mobile/app/sign-up").permitAll()
            .antMatchers("/v1/**").permitAll()
            .anyRequest().authenticated()
            .and()
        .formLogin()
            .loginPage("/")
            .loginProcessingUrl("/loginprocess")
            .failureUrl("/?loginFailure=true")
            .permitAll();
}

我正在考虑添加一个pre-auth过滤器,它检查请求中的令牌然后设置安全上下文(这是否意味着将跳过正常的后续身份验证?),但是,超出了我的正常用户/密码基于令牌的安全性没有做太多,但基于其他一些例子,我想出了以下内容:

安全配置:

@Override protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf()
                .disable()
            .addFilter(restAuthenticationFilter())
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
                .exceptionHandling().authenticationEntryPoint(new Http403ForbiddenEntryPoint()).and()
                .antMatcher("/v1/**")
            .authorizeRequests()
                .antMatchers("/resources/**").permitAll()
                .antMatchers("/mobile/app/sign-up").permitAll()
                .antMatchers("/v1/**").permitAll()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/")
                .loginProcessingUrl("/loginprocess")
                .failureUrl("/?loginFailure=true")
                .permitAll();
    }

我的定制休息过滤器:

public class RestAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

    public RestAuthenticationFilter(String defaultFilterProcessesUrl) {
        super(defaultFilterProcessesUrl);
    }

    private final String HEADER_SECURITY_TOKEN = "X-Token"; 
    private String token = "";


    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;

        this.token = request.getHeader(HEADER_SECURITY_TOKEN);

        //If we have already applied this filter - not sure how that would happen? - then just continue chain
        if (request.getAttribute(FILTER_APPLIED) != null) {
            chain.doFilter(request, response);
            return;
        }

        //Now mark request as completing this filter
        request.setAttribute(FILTER_APPLIED, Boolean.TRUE);

        //Attempt to authenticate
        Authentication authResult;
        authResult = attemptAuthentication(request, response);
        if (authResult == null) {
            unsuccessfulAuthentication(request, response, new LockedException("Forbidden"));
        } else {
            successfulAuthentication(request, response, chain, authResult);
        }
    }

    /**
     * Attempt to authenticate request - basically just pass over to another method to authenticate request headers 
     */
    @Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
        AbstractAuthenticationToken userAuthenticationToken = authUserByToken();
        if(userAuthenticationToken == null) throw new AuthenticationServiceException(MessageFormat.format("Error | {0}", "Bad Token"));
        return userAuthenticationToken;
    }


    /**
     * authenticate the user based on token, mobile app secret & user agent
     * @return
     */
    private AbstractAuthenticationToken authUserByToken() {
        AbstractAuthenticationToken authToken = null;
        try {
            // TODO - just return null - always fail auth just to test spring setup ok
            return null;
        } catch (Exception e) {
            logger.error("Authenticate user by token error: ", e);
        }
        return authToken;
    }

以上实际上导致应用启动错误说: authenticationManager must be specified 任何人都可以告诉我如何最好地做到这一点 - pre_auth过滤器是最好的方法吗?


EDIT

我写了我发现的内容,以及我是如何使用Spring-security(包括代码)实现标准令牌实现(不是OAuth)的

Overview of the problem and approach/solution

Implementing the solution with Spring-security

希望它能帮助其他人..

1 回答

  • 7

    我相信你提到的错误只是因为你使用的 AbstractAuthenticationProcessingFilter 基类需要 AuthenticationManager . 如果您不打算使用它,可以将其设置为no-op,或者直接实现 Filter . 如果您的 Filter 可以对请求进行身份验证并设置 SecurityContext ,那么通常会跳过下游处理(这取决于下游过滤器的实现,但我在您的应用中看不到任何奇怪的内容,因此它们可能都是这样的) .

    如果我是你,我可能会考虑将API endpoints 放在一个完全独立的过滤器链中(另一个 WebSecurityConfigurerAdapter bean) . 但这只会让事情变得更容易阅读,而不一定是至关重要的 .

    您可能会发现(正如评论中所建议的那样)您最终会重新发明轮子,但尝试没有任何损害,您可能会在此过程中了解有关Spring和Security的更多信息 .

    附加:github approach非常有趣:用户只需在基本身份验证中使用令牌作为密码,服务器不需要自定义过滤器( BasicAuthenticationFilter 就可以了) .

相关问题