1. 程式人生 > >SpringOauth2.0 使用者名稱密碼驗證方式(二)

SpringOauth2.0 使用者名稱密碼驗證方式(二)

1.Oauth2.0 使用者名稱密碼認證流程

image

  • (A)使用者向客戶端提供使用者名稱和密碼。
  • (B)客戶端將使用者名稱和密碼發給認證伺服器,向後者請求令牌。
  • (C)認證伺服器確認無誤後,向客戶端提供訪問令牌。 請求示例
  • (B)步驟:客戶端發出https請求

使用者名稱密碼認證方式,其實是對Code認證方式的高度封裝,將其中的使用者確認授權的步驟直接整合到:使用者向客戶端提供使用者名稱和密碼

在這種模式下,使用者必須對客戶端絕對信任,才能提供使用者名稱和密碼認證。

2.程式碼實現

@Configuration
@EnableAuthorizationServer
public class OAuth2ServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private AuthenticationManager authenticationManager;
    
    @Override
    public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
        oauthServer
                .realm("oauth2-resources")
                //url:/oauth/token_key,exposes public key for token verification if using JWT tokens
                .tokenKeyAccess("permitAll()")
                //url:/oauth/check_token allow check token
                .checkTokenAccess("isAuthenticated()")
                .allowFormAuthenticationForClients();
    }

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

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                .withClient("client")
                .secret(passwordEncoder.encode("secret"))
                .redirectUris("http://example.com")
                // 客戶端認證方式相容了5種模式
                .authorizedGrantTypes("authorization_code", "client_credentials", "refresh_token",
                        "password", "implicit")
                .scopes("all")
                .resourceIds("oauth2-resource")
                .accessTokenValiditySeconds(1200)
                .refreshTokenValiditySeconds(50000);
    }
}

認證方式相容了5種認證方式,使用者名稱密碼模式直接用上述程式碼即可。

3.請求認證

3.1 請求認證access_token
curl -i -d "grant_type=password&username=hello1&password=123456&scope=all" -u "client:secret" -X POST http://localhost:8080/oauth/token

引數說明:

grant_type:授權型別,此處的值固定為"password",必選項。  
username:使用者名稱,必選項。  
password:使用者的密碼,必選項。  
scope:許可權範圍,可選項。

返回結果:

{
    "access_token": "99430e52-9d76-4f2c-af98-b1667657eb23",
    "token_type": "bearer",
    "refresh_token": "8b6c262d-22cb-4e5b-af08-a32cbee5c5c2",
    "expires_in": 1199,
    "scope": "all"
}

結果引數說明:

access_token:訪問令牌,必選項。  
token_type:令牌型別,該值大小寫不敏感,必選項。  
expires_in:過期時間,單位為秒。如果省略該引數,必須其他方式設定過期時間。
refresh_token:更新令牌,用來獲取下一次的訪問令牌,可選項。