Spring Security OAuth2,它决定了安全性? [英] Spring Security OAuth2, which decides security?

查看:31
本文介绍了Spring Security OAuth2,它决定了安全性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试使用 Dave Syer 的指南并从 JHipster 获得一些灵感来实现 OAuth2 身份验证服务器.但我无法弄清楚它们是如何协同工作的.

I've been trying to implement a OAuth2 authentication server using the guides by Dave Syer with some inspiration from JHipster. But I can't figure out how it all works together.

当我使用 ResourceServerConfigurerAdapter 时,使用 WebSecurityConfigurerAdapter 的安全设置似乎被覆盖了.

It looks like the security setup using the WebSecurityConfigurerAdapter is overwritten when I use ResourceServerConfigurerAdapter.

@Configuration
@EnableResourceServer
public class OAuth2ResourceConfig extends ResourceServerConfigurerAdapter {

    private TokenExtractor tokenExtractor = new BearerTokenExtractor();

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
                .addFilterAfter(contextClearer(), AbstractPreAuthenticatedProcessingFilter.class)
                .authorizeRequests()
                .anyRequest().authenticated().and().httpBasic();
    }

    private OncePerRequestFilter contextClearer() {
        return new OncePerRequestFilter() {
            @Override
            protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
                if (tokenExtractor.extract(request) == null) {
                    SecurityContextHolder.clearContext();
                }
                filterChain.doFilter(request, response);
            }
        };
    }

@Component
public class CustomWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {

    private final AuthenticationManager authenticationManager;

    @Autowired
    public CustomWebSecurityConfigurerAdapter(AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
                .parentAuthenticationManager(authenticationManager);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .formLogin()
                    .loginPage("/login").permitAll()
                .and()
                    .authorizeRequests().antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
                .and()
                    .requestMatchers().antMatchers("/login", "/oauth/authorize", "/oauth/confirm_access")
                .and()
                    .authorizeRequests().anyRequest().authenticated();
    }
}

这是取自几个不同示例的代码,因此它们可能无法很好地混合.但是我找不到 OAuth2 的好的文档/示例列表(不像 Spring Boot 有很棒的文档),所以我在理解你如何组合在一起时遇到了问题.如果我不将 loginForm 添加到 ResourceServerConfigurerAdapter,它只会给我未经授权的信息.但我在 WebSecurityConfigurererAdapter 中将其定义为 permitAll().

This is code taken from a few different examples, so they might not mix that well. But I can't find a good documentation/example list for OAuth2 (unlike Spring Boot which has a awesome documentation), so I'm having problems understanding how thye all fit together. If I don't add the loginForm to the ResourceServerConfigurerAdapter, it will just give me unauthorized. But I defined it in the WebSecurityConfigurererAdapter as permitAll().

这是 AuthorizationServerConfigurerAdapter:

This is the AuthorizationServerConfigurerAdapter:

@Configuration
@EnableAuthorizationServer
public class OAuth2AuthorizationConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtAccessTokenConverter jwtAccessTokenConverter;

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                .withClient("acme")
                .secret("acmesecret")
                .authorizedGrantTypes("authorization_code", "refresh_token",
                        "password").scopes("openid");
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints)  throws Exception {
        endpoints.authenticationManager(authenticationManager).accessTokenConverter(jwtAccessTokenConverter);
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
        oauthServer.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()");
    }
}

我做错了什么吗?我是否必须在 ResourceServerConfigurerAdapter 中设置所有安全性?我还需要 WebSecurityConfigurerAdapter 吗?

Anything I'm doing wrong? Do I have to setup all the security within the ResourceServerConfigurerAdapter? Do I even need the WebSecurityConfigurerAdapter anymore?

如果有人知道任何指南、教程、博客或任何可以帮助我了解其工作原理的类似内容,我将不胜感激.

If anyone know any guides, tutorials, blogs or anything alike that might help me wrap my head around how this works, that would be greatly appreciated.

亲切的问候,肯尼斯.

推荐答案

您需要一个 WebSecurityConfigurerAdapter 来保护/authorize 端点并为用户提供一种验证方式.Spring Boot 应用程序会为你做这件事(通过添加它自己的 WebSecurityConfigurerAdapter 和 HTTP 基本身份验证).默认情况下,它会创建一个 order=0 的过滤器链,并保护所有资源,除非您提供请求匹配器.@EnableResourceServer 做了类似的事情,但它添加的过滤器链默认为 order=3.WebSecurityConfigurerAdapter 有一个 @Order(100) 注释.因此,首先将检查 ResourceServer(身份验证),然后将检查您在 WebSecurityConfigureAdapter 扩展中的检查.

You need a WebSecurityConfigurerAdapter to secure the /authorize endpoint and to provide a way for users to authenticate. A Spring Boot application would do that for you (by adding its own WebSecurityConfigurerAdapter with HTTP basic auth). It creates a filter chain with order=0 by default, and protects all resources unless you provide a request matcher. The @EnableResourceServer does something similar, but the filter chain it adds is at order=3 by default. WebSecurityConfigurerAdapter has an @Order(100) annotation. So first the ResourceServer will be checked (authentication) and then your checks in your enxtension of WebSecurityConfigureAdapter will be checked.

您的配置看起来很合理(登录链优先,但只匹配一小组请求).

Your configuration looks sane (the login chain takes precedence, but only matches a small set of requests).

这篇关于Spring Security OAuth2,它决定了安全性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆