springcloud整合Oauth2自定义登录/登出接口

本文详细描述了使用SpringSecurityOAuth2进行用户登录(基于username/password方式)、获取和使用OAuth2AccessToken,以及登出操作的过程,包括自定义登出接口和处理OAuth2常见问题。

我使用的是password模式,并配置了token模式

一、登录 (这里我使用的示例是用户名密码认证方式)

1.  Oath2提供默认登录授权接口 

org.springframework.security.oauth2.provider.endpoint.postAccess;

Tokenpublic ResponseEntity<OAuth2AccessToken> postAccessToken( Principal principal, @RequestParam Map<String, String> parameters);

入参: principal,parameters

1. principal:代表的是认证信息

2.parameters:携带信息

这里直接用UsernamePasswordAuthenticationToken生成凭证并构造出需要的参数

UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken("c1","secret",authorities);
HashMap<String, String> param= new HashMap<>();
param.put("grant_type","password");
param.put("username",user.getUsername());
param.put("password",user.getPassword());

usernamePasswordAuthenticationToken.setDetails(param);
tokenEndpoint.postAccessToken(usernamePasswordAuthenticationToken, stringHashMap)

在postAccessToken方法中

TokenRequest tokenRequest = getOAuth2RequestFactory().createTokenRequest(parameters, authenticatedClient);

就是根据传入的param和token进行构造。

OAuth2AccessToken token = getTokenGranter().grant(tokenRequest.getGrantType(), tokenRequest);

根据tokenRequest去生成token

到这里token就会生成完毕。

二、登出

String access = tokenObj.get("accessToken");
String refresh = tokenObj.get("refreshToken");
OAuth2AccessToken accessToken = tokenStore.readAccessToken(access);
OAuth2RefreshToken refreshToken = tokenStore.readRefreshToken(refresh);
tokenStore.removeRefreshToken(refreshToken);
tokenStore.removeAccessToken(accessToken);

自定义登出接口,然后传入token和刷新token利用tokenStore进行删除即可。

Oauth2 有许多的坑需要去填,如果有需要请留言,我会出一期完整博客记录Oauth2认证与授权

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值