您的位置:首页 > 编程语言 > Java开发

SpringOauth2.0 用户名密码验证方式(二)

2018-10-22 09:46 621 查看
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u014730165/article/details/83268580

1.Oauth2.0 用户名密码认证流程

  • (A)用户向客户端提供用户名和密码。
  • (B)客户端将用户名和密码发给认证服务器,向后者请求令牌。
  • (C)认证服务器确认无误后,向客户端提供访问令牌。
    请求示例
  • (B)步骤:客户端发出https请求

用户名密码认证方式,其实是对Code认证方式的高度封装,将其中的用户确认授权的步骤直接整合到:用户向客户端提供用户名和密码

在这种模式下,用户必须对客户端绝对信任,才能提供用户名和密码认证。

2.代码实现

在上一片文章中:
SpringOauth2 Authorization_code 模式(一)实现了对code码的认证,其中核心代码client配置模块如下:

@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:更新令牌,用来获取下一次的访问令牌,可选项。
阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: