Spring oauth2 基本认证

Posted

技术标签:

【中文标题】Spring oauth2 基本认证【英文标题】:Spring oauth2 basic authentication 【发布时间】:2018-09-04 23:03:34 【问题描述】:

我正在尝试使用 OAuth2 实现开发具有 Spring Security 的 rest api。但是如何删除基本身份验证。我只想将用户名和密码发送到正文并在邮递员上获取令牌。

@Configuration
public class OAuthServerConfigration 

private static final String SERVER_RESOURCE_ID = "oauth2-server";

private static InMemoryTokenStore tokenStore = new InMemoryTokenStore();


@Configuration
@EnableResourceServer
protected static class ResourceServer extends ResourceServerConfigurerAdapter 

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception 
        resources.resourceId(SERVER_RESOURCE_ID).stateless(false);
    

    @Override
    public void configure(HttpSecurity http) throws Exception 
         http.anonymous().disable().requestMatchers().antMatchers("/api/**").and().authorizeRequests().antMatchers("/api/**").access("#oauth2.hasScope('read')");
    


@Configuration
@EnableAuthorizationServer
protected static class AuthConfig extends AuthorizationServerConfigurerAdapter 

    @Autowired
    private AuthenticationManager authenticationManager;


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

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception 
        clients.inMemory()
            .withClient("client")
            .secret("$2a$10$5OkeCLKNs/BkdO0qcYRri.MdIcKhFvElAllhPgLfRQqG7wkEiPmq2")
                .authorizedGrantTypes("password","authorization_code","refresh_token")
                .authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT")
              .scopes("read", "write", "trust")
                .resourceIds(SERVER_RESOURCE_ID)
                  //.accessTokenValiditySeconds(ONE_DAY)
                  .accessTokenValiditySeconds(300)
                  .refreshTokenValiditySeconds(50);

    


    @Override
    public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception 

        oauthServer
                // we're allowing access to the token only for clients with 'ROLE_TRUSTED_CLIENT' authority
                .tokenKeyAccess("hasAuthority('ROLE_TRUSTED_CLIENT')")
                .checkTokenAccess("hasAuthority('ROLE_TRUSTED_CLIENT')");

    

 



@Configuration
@Order(2)
public static class ApiLoginConfig extends 
WebSecurityConfigurerAdapter   
    @Autowired
    DataSource dataSource;

    @Autowired
    ClientDetailsService clientDetailsService;


    @Override
    public void configure(WebSecurity web) throws Exception 
        web.ignoring().antMatchers("/oauth/**");
    

    @Override
    protected void configure(HttpSecurity http) throws Exception 

        http.httpBasic().disable().csrf().disable().antMatcher("/oauth/token").authorizeRequests().anyRequest().permitAll();


    
    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception 
        return super.authenticationManagerBean();
    

    @Bean
    public TokenStore tokenStore() 
        return new InMemoryTokenStore();
    

    @Bean
    @Autowired
    public TokenStoreUserApprovalHandler userApprovalHandler(TokenStore tokenStore)
        TokenStoreUserApprovalHandler handler = new TokenStoreUserApprovalHandler();
        handler.setTokenStore(tokenStore);
        handler.setRequestFactory(new DefaultOAuth2RequestFactory(clientDetailsService));
        handler.setClientDetailsService(clientDetailsService);
        return handler;
    

    @Bean
    @Autowired
    public ApprovalStore approvalStore(TokenStore tokenStore) throws Exception 
        TokenApprovalStore store = new TokenApprovalStore();
        store.setTokenStore(tokenStore);
        return store;
    

想要移除基本认证,并从邮递员的body标签中发送用户名密码以获取令牌

我遇到了一些问题 “错误”:“未经授权”, "error_description": "没有客户端身份验证。尝试添加适当的身份验证过滤器。"

【问题讨论】:

Spring security oauth2 - Can't access /oauth/token route的可能重复 【参考方案1】:

在你的 @EnableAuthorizationServer 配置类中的方法:-

@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer)

尝试添加以下内容:-

oauthServer.allowFormAuthenticationForClients()

完成此操作后,您必须调用 oauth get token url,如下所示:-

URL 将与 http(s)://HOST_NAME/oauth/token 相同

HTTP 方法类型现在将是 POST

标题:-

Content-Type=application/x-www-form-urlencoded

参数将是 postman 正文中 x-www-form-urlencoded 中的键值对

对于client_credentials grant_type:-

grant_type=client_credentials
client_id=client_id_value
client_secret=client_secret_value
scope=scopes

对于密码grant_type:-

grant_type=password
client_id=client_id_value
client_secret=client_secret_value
scope=scopes
username=username
password=password

范围将在此处以逗号分隔

【讨论】:

grant_type = 密码

以上是关于Spring oauth2 基本认证的主要内容,如果未能解决你的问题,请参考以下文章

Spring Security OAuth2.0认证授权

Spring Security OAuth2.0认证授权

Spring Security OAuth2.0认证授权

Spring Security OAuth2.0认证授权

Spring Security Oauth2架构学习

聊聊spring security oauth2的几个endpoint的认证