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

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

问题描述

我一直在尝试使用Dave Syer的指南来实现OAuth2身份验证服务器,并从JHipster那里获得一些启发.但是我不知道它们是如何协同工作的.

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中将其定义为allowAll().

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应用程序将为您做到这一点(通过使用HTTP基本身份验证添加其自己的WebSecurityConfigurerAdapter).默认情况下,它将创建一个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天全站免登陆