【问题标题】:How to customize OAuth service provider in Spring security?如何在 Spring Security 中自定义 OAuth 服务提供者?
【发布时间】:2016-07-26 23:19:37
【问题描述】:

我正在使用 Spring Boot 应用程序并且我有休息控制器。我刚刚在春季开始使用 OAuth 2.0 来保护我的 API。这是我拥有的配置类。

@Configuration
@EnableResourceServer
public class OAuth2ResourceServerConfig extends ResourceServerConfigurerAdapter  {

    private static final String HU_REST_RESOURCE_ID = "rest_api";

    @Autowired
    DataSource dataSource;

    @Bean
    public TokenStore tokenStore() {
        return new JdbcTokenStore(dataSource);
    }


    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        resources.resourceId(HU_REST_RESOURCE_ID).stateless(false);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {

    //define URL patterns to enable OAuth2 security 

        http.
        requestMatchers().antMatchers("/user/**").and().
        authorizeRequests().antMatchers("/user/**").access("#oauth2.hasScope('read') or (!#oauth2.isOAuth() and hasRole('ROLE_USER'))");
    }

}

@Configuration
@EnableAuthorizationServer
public class OAuth2AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter  {


    @Autowired
    DataSource dataSource;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {


    clients.inMemory()
              .withClient("my-trusted-client")
                .authorizedGrantTypes("password","refresh_token")
                .authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT")
                .scopes("read", "write", "trust")
                .accessTokenValiditySeconds(60)
                .refreshTokenValiditySeconds(600)
        .and()
              .withClient("my-trusted-client-with-secret")
                .authorizedGrantTypes("password", "authorization_code", "refresh_token", "implicit")
                .authorities("ROLE_USER")
                .scopes("read", "write", "trust")
                .accessTokenValiditySeconds(60)
                .refreshTokenValiditySeconds(600);
    }


    @Bean
    public TokenStore tokenStore() {
        return new JdbcTokenStore(dataSource); // access and refresh tokens will be maintain in database
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.tokenStore(tokenStore()).authenticationManager(authenticationManager);

    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
        oauthServer.allowFormAuthenticationForClients();
    }

}


@Configuration
public class GlobalAuthenticationConfig extends GlobalAuthenticationConfigurerAdapter {

    @Override
    public void init(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("user1").password("user1123").roles("USER");
         auth.inMemoryAuthentication().withUser("user2").password("user2123").roles("ADMIN");
    }
}

现在,当我点击 URL http://localhost:8080/oauth/token?grant_type=password&client_id=my-trusted-client-with-secret&username=user1&password=user1123 时,我会得到以下访问令牌和刷新令牌,

{
    "access_token": "87379d65-6012-4484-ba6f-e4c61766ede3",
    "token_type": "bearer",
    "refresh_token": "8b0d0ae3-0855-4465-9d89-a1c31c031b8a",
    "expires_in": 59,
    "scope": "read write trust"
}

我的问题是为什么有人会将凭据作为查询参数传递?我们可以发出一个 post 请求并在一个对象中作为 POST 请求发送所需的参数吗?如果是,我该怎么做? 我的第二个问题是,我在这里使用内存身份验证,即两个用户在代码中被硬编码。如何让它从数据库中检查用户凭据?

【问题讨论】:

    标签: java spring spring-mvc oauth spring-security


    【解决方案1】:

    当您使用 https(您应该这样做)时,完整的查询在通过网络发送之前会被加密,如下所述: Are querystring parameters secure in HTTPS (HTTP + SSL)?

    关于第二个问题,如果您希望 Spring 从数据库中检查授权用户,则必须创建一个继承自 UserDetailsManagerhttp://docs.spring.io/autorepo/docs/spring-security/4.0.3.RELEASE/apidocs/org/springframework/security/provisioning/UserDetailsManager.html 的类

    然后您可以实现它的不同方法,特别是它从 UserDetailsService(由 Spring 身份验证管理器使用)实现的 loadUserByUsername(String username),使用代码查询您的数据库以获取相关数据。

    另一个问题描述了如何将该管理器添加到您的 Spring 应用程序 How to make a UserDetailsManager available as a bean

    【讨论】:

      猜你喜欢
      • 2014-04-24
      • 2016-01-08
      • 2013-11-01
      • 2011-08-09
      • 2015-02-19
      • 2011-04-25
      • 2021-09-04
      • 2019-07-23
      • 1970-01-01
      相关资源
      最近更新 更多