新增 sso 页面

pull/2/head
YunaiV 2022-05-24 00:01:30 +08:00
parent ed847ac2ee
commit d18463866e
13 changed files with 215 additions and 95 deletions

View File

@ -1,10 +1,15 @@
### 请求 /system/oauth2/authorize 接口 => 成功
GET {{baseUrl}}/system/oauth2/authorize?clientId=default
Authorization: Bearer {{token}}
tenant-id: {{adminTenentId}}
### 请求 /system/oauth2/authorize + token 接口 => 成功
POST {{baseUrl}}/system/oauth2/authorize
Content-Type: application/x-www-form-urlencoded
Authorization: Bearer {{token}}
tenant-id: {{adminTenentId}}
response_type=token&client_id=default&scope={"user_info": true}&redirect_uri=https://www.iocoder.cn&auto_approve=true
response_type=token&client_id=default&scope={"user.read": true}&redirect_uri=https://www.iocoder.cn&auto_approve=true
### 请求 /system/oauth2/authorize + code 接口 => 成功
POST {{baseUrl}}/system/oauth2/authorize
@ -12,7 +17,7 @@ Content-Type: application/x-www-form-urlencoded
Authorization: Bearer {{token}}
tenant-id: {{adminTenentId}}
response_type=code&client_id=default&scope={"user.read": true}&redirect_uri=https://www.iocoder.cn&auto_approve=true
response_type=code&client_id=default&scope={"user.read": true}&redirect_uri=https://www.iocoder.cn&auto_approve=false
### 请求 /system/oauth2/token + code 接口 => 成功
POST {{baseUrl}}/system/oauth2/token

View File

@ -11,14 +11,16 @@ import cn.iocoder.yudao.framework.common.util.http.HttpUtils;
import cn.iocoder.yudao.framework.common.util.json.JsonUtils;
import cn.iocoder.yudao.framework.operatelog.core.annotations.OperateLog;
import cn.iocoder.yudao.module.system.controller.admin.oauth2.vo.open.OAuth2OpenAccessTokenRespVO;
import cn.iocoder.yudao.module.system.controller.admin.oauth2.vo.open.OAuth2OpenAuthorizeInfoRespVO;
import cn.iocoder.yudao.module.system.controller.admin.oauth2.vo.open.OAuth2OpenCheckTokenRespVO;
import cn.iocoder.yudao.module.system.controller.admin.oauth2.vo.open.user.OAuth2OpenUserInfoRespVO;
import cn.iocoder.yudao.module.system.controller.admin.user.vo.profile.UserProfileUpdateReqVO;
import cn.iocoder.yudao.module.system.controller.admin.oauth2.vo.open.user.OAuth2OpenUserUpdateReqVO;
import cn.iocoder.yudao.module.system.convert.oauth2.OAuth2OpenConvert;
import cn.iocoder.yudao.module.system.dal.dataobject.oauth2.OAuth2AccessTokenDO;
import cn.iocoder.yudao.module.system.dal.dataobject.oauth2.OAuth2ClientDO;
import cn.iocoder.yudao.module.system.dal.dataobject.dept.DeptDO;
import cn.iocoder.yudao.module.system.dal.dataobject.dept.PostDO;
import cn.iocoder.yudao.module.system.dal.dataobject.oauth2.OAuth2AccessTokenDO;
import cn.iocoder.yudao.module.system.dal.dataobject.oauth2.OAuth2ApproveDO;
import cn.iocoder.yudao.module.system.dal.dataobject.oauth2.OAuth2ClientDO;
import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.yudao.module.system.enums.auth.OAuth2GrantTypeEnum;
import cn.iocoder.yudao.module.system.service.dept.DeptService;
@ -91,7 +93,7 @@ public class OAuth2OpenController {
* client_id + client_secret
*/
@PostMapping("/token")
@ApiOperation(value = "获得访问令牌", notes = "适合 code 授权码模式,或者 implicit 简化模式;在 authorize.vue 单点登录界面被【获取】调用")
@ApiOperation(value = "获得访问令牌", notes = "适合 code 授权码模式,或者 implicit 简化模式;在 sso.vue 单点登录界面被【获取】调用")
@ApiImplicitParams({
@ApiImplicitParam(name = "grant_type", required = true, value = "授权类型", example = "code", dataTypeClass = String.class),
@ApiImplicitParam(name = "code", value = "授权范围", example = "userinfo.read", dataTypeClass = String.class),
@ -173,7 +175,7 @@ public class OAuth2OpenController {
@RequestParam("token") String token) {
// 校验客户端
String[] clientIdAndSecret = obtainBasicAuthorization(request);
OAuth2ClientDO client = oauth2ClientService.validOAuthClientFromCache(clientIdAndSecret[0], clientIdAndSecret[1],
oauth2ClientService.validOAuthClientFromCache(clientIdAndSecret[0], clientIdAndSecret[1],
null, null, null);
// 校验令牌
@ -182,46 +184,36 @@ public class OAuth2OpenController {
return success(OAuth2OpenConvert.INSTANCE.convert2(accessTokenDO));
}
// GET oauth/authorize AuthorizationEndpoint TODO
/**
* Spring Security OAuth AuthorizationEndpoint authorize
*/
@GetMapping("/authorize")
@ApiOperation(value = "获得授权信息", notes = "适合 code 授权码模式,或者 implicit 简化模式;在 authorize.vue 单点登录界面被【获取】调用")
@ApiImplicitParams({
@ApiImplicitParam(name = "response_type", required = true, value = "响应类型", example = "code", dataTypeClass = String.class),
@ApiImplicitParam(name = "client_id", required = true, value = "客户端编号", example = "tudou", dataTypeClass = String.class),
@ApiImplicitParam(name = "scope", value = "授权范围", example = "userinfo.read", dataTypeClass = String.class), // 多个使用空格分隔
@ApiImplicitParam(name = "redirect_uri", required = true, value = "重定向 URI", example = "https://www.iocoder.cn", dataTypeClass = String.class),
@ApiImplicitParam(name = "state", example = "123321", dataTypeClass = String.class)
})
public CommonResult<Object> authorize(@RequestParam("response_type") String responseType,
@RequestParam("client_id") String clientId,
@RequestParam(value = "scope", required = false) String scope,
@RequestParam("redirect_uri") String redirectUri,
@RequestParam(value = "state", required = false) String state) {
List<String> scopes = StrUtil.split(scope, ' ');
@ApiOperation(value = "获得授权信息", notes = "适合 code 授权码模式,或者 implicit 简化模式;在 sso.vue 单点登录界面被【获取】调用")
@ApiImplicitParam(name = "clientId", required = true, value = "客户端编号", example = "tudou", dataTypeClass = String.class)
public CommonResult<OAuth2OpenAuthorizeInfoRespVO> authorize(@RequestParam("clientId") String clientId) {
// 0. 校验用户已经登录。通过 Spring Security 实现
// 1.1 校验 responseType 是否满足 code 或者 token 值
OAuth2GrantTypeEnum grantTypeEnum = getGrantTypeEnum(responseType);
// 1.2 校验 redirectUri 重定向域名是否合法 + 校验 scope 是否在 Client 授权范围内
oauth2ClientService.validOAuthClientFromCache(clientId, null,
grantTypeEnum.getGrantType(), scopes, redirectUri);
// 3. 不满足自动授权,则返回授权相关的展示信息
return null;
// 1. 获得 Client 客户端的信息
OAuth2ClientDO client = oauth2ClientService.validOAuthClientFromCache(clientId, null,
null, null, null);
// 2. 获得用户已经授权的信息
List<OAuth2ApproveDO> approves = oauth2ApproveService.getApproveList(getLoginUserId(), getUserType(), clientId);
// 拼接返回
return success(OAuth2OpenConvert.INSTANCE.convert(client, approves));
}
/**
* Spring Security OAuth AuthorizationEndpoint approveOrDeny
*
* autoApprove = true
* authorize.vue OAuth2Client scope
* sso.vue OAuth2Client scope
* autoApprove = false
* authorize.vue scope approved true false
* sso.vue scope approved true false
*
* Axios 302 Spring Security OAuth URL
*/
@PostMapping("/authorize")
@ApiOperation(value = "申请授权", notes = "适合 code 授权码模式,或者 implicit 简化模式;在 authorize.vue 单点登录界面被【提交】调用")
@ApiOperation(value = "申请授权", notes = "适合 code 授权码模式,或者 implicit 简化模式;在 sso.vue 单点登录界面被【提交】调用")
@ApiImplicitParams({
@ApiImplicitParam(name = "response_type", required = true, value = "响应类型", example = "code", dataTypeClass = String.class),
@ApiImplicitParam(name = "client_id", required = true, value = "客户端编号", example = "tudou", dataTypeClass = String.class),
@ -346,7 +338,7 @@ public class OAuth2OpenController {
@PutMapping("/user/update")
@ApiOperation("更新用户基本信息")
@PreAuthorize("@ss.hasScope('user.write')")
public CommonResult<Boolean> updateUserInfo(@Valid @RequestBody UserProfileUpdateReqVO reqVO) {
public CommonResult<Boolean> updateUserInfo(@Valid @RequestBody OAuth2OpenUserUpdateReqVO reqVO) {
// 这里将 UserProfileUpdateReqVO =》UserProfileUpdateReqVO 对象,实现接口的复用。
// 主要是AdminUserService 没有自己的 BO 对象,所以复用只能这么做
userService.updateUserProfile(getLoginUserId(), OAuth2OpenConvert.INSTANCE.convert(reqVO));

View File

@ -18,39 +18,39 @@ import java.util.List;
@Data
public class OAuth2ClientBaseVO {
@ApiModelProperty(value = "客户端编号", required = true)
@ApiModelProperty(value = "客户端编号", required = true, example = "tudou")
@NotNull(message = "客户端编号不能为空")
private String clientId;
@ApiModelProperty(value = "客户端密钥", required = true)
@ApiModelProperty(value = "客户端密钥", required = true, example = "fan")
@NotNull(message = "客户端密钥不能为空")
private String secret;
@ApiModelProperty(value = "应用名", required = true)
@ApiModelProperty(value = "应用名", required = true, example = "土豆")
@NotNull(message = "应用名不能为空")
private String name;
@ApiModelProperty(value = "应用图标", required = true)
@ApiModelProperty(value = "应用图标", required = true, example = "https://www.iocoder.cn/xx.png")
@NotNull(message = "应用图标不能为空")
@URL(message = "应用图标的地址不正确")
private String logo;
@ApiModelProperty(value = "应用描述")
@ApiModelProperty(value = "应用描述", example = "我是一个应用")
private String description;
@ApiModelProperty(value = "状态", required = true)
@ApiModelProperty(value = "状态", required = true, example = "1", notes = "参见 CommonStatusEnum 枚举")
@NotNull(message = "状态不能为空")
private Integer status;
@ApiModelProperty(value = "访问令牌的有效期", required = true)
@ApiModelProperty(value = "访问令牌的有效期", required = true, example = "8640")
@NotNull(message = "访问令牌的有效期不能为空")
private Integer accessTokenValiditySeconds;
@ApiModelProperty(value = "刷新令牌的有效期", required = true)
@ApiModelProperty(value = "刷新令牌的有效期", required = true, example = "8640000")
@NotNull(message = "刷新令牌的有效期不能为空")
private Integer refreshTokenValiditySeconds;
@ApiModelProperty(value = "可重定向的 URI 地址", required = true)
@ApiModelProperty(value = "可重定向的 URI 地址", required = true, example = "https://www.iocoder.cn")
@NotNull(message = "可重定向的 URI 地址不能为空")
private List<@NotEmpty(message = "重定向的 URI 不能为空")
@URL(message = "重定向的 URI 格式不正确") String> redirectUris;

View File

@ -10,10 +10,10 @@ import cn.iocoder.yudao.framework.common.pojo.PageParam;
@ToString(callSuper = true)
public class OAuth2ClientPageReqVO extends PageParam {
@ApiModelProperty(value = "应用名")
@ApiModelProperty(value = "应用名", example = "土豆", notes = "模糊匹配")
private String name;
@ApiModelProperty(value = "状态")
@ApiModelProperty(value = "状态", example = "1", notes = "参见 CommonStatusEnum 枚举")
private Integer status;
}

View File

@ -14,7 +14,7 @@ import java.util.Date;
@ToString(callSuper = true)
public class OAuth2ClientRespVO extends OAuth2ClientBaseVO {
@ApiModelProperty(value = "编号", required = true)
@ApiModelProperty(value = "编号", required = true, example = "1024")
private Long id;
@ApiModelProperty(value = "创建时间", required = true)

View File

@ -14,7 +14,7 @@ import javax.validation.constraints.NotNull;
@ToString(callSuper = true)
public class OAuth2ClientUpdateReqVO extends OAuth2ClientBaseVO {
@ApiModelProperty(value = "编号", required = true)
@ApiModelProperty(value = "编号", required = true, example = "1024")
@NotNull(message = "编号不能为空")
private Long id;

View File

@ -0,0 +1,39 @@
package cn.iocoder.yudao.module.system.controller.admin.oauth2.vo.open;
import cn.iocoder.yudao.framework.common.core.KeyValue;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
@ApiModel("管理后台 - 授权页的信息 Response VO")
@Data
@NoArgsConstructor
@AllArgsConstructor
public class OAuth2OpenAuthorizeInfoRespVO {
/**
*
*/
private Client client;
@ApiModelProperty(value = "scope 的选中信息", required = true, notes = "使用 List 保证有序性Key 是 scopeValue 为是否选中")
private List<KeyValue<String, Boolean>> scopes;
@Data
@NoArgsConstructor
@AllArgsConstructor
public static class Client {
@ApiModelProperty(value = "应用名", required = true, example = "土豆")
private String name;
@ApiModelProperty(value = "应用图标", required = true, example = "https://www.iocoder.cn/xx.png")
private String logo;
}
}

View File

@ -1,20 +1,28 @@
package cn.iocoder.yudao.module.system.convert.oauth2;
import cn.iocoder.yudao.framework.common.core.KeyValue;
import cn.iocoder.yudao.framework.common.enums.UserTypeEnum;
import cn.iocoder.yudao.framework.common.util.collection.CollectionUtils;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.system.controller.admin.oauth2.vo.open.OAuth2OpenAccessTokenRespVO;
import cn.iocoder.yudao.module.system.controller.admin.oauth2.vo.open.OAuth2OpenAuthorizeInfoRespVO;
import cn.iocoder.yudao.module.system.controller.admin.oauth2.vo.open.OAuth2OpenCheckTokenRespVO;
import cn.iocoder.yudao.module.system.controller.admin.oauth2.vo.open.user.OAuth2OpenUserInfoRespVO;
import cn.iocoder.yudao.module.system.controller.admin.oauth2.vo.open.user.OAuth2OpenUserUpdateReqVO;
import cn.iocoder.yudao.module.system.controller.admin.user.vo.profile.UserProfileUpdateReqVO;
import cn.iocoder.yudao.module.system.dal.dataobject.oauth2.OAuth2AccessTokenDO;
import cn.iocoder.yudao.module.system.dal.dataobject.dept.DeptDO;
import cn.iocoder.yudao.module.system.dal.dataobject.dept.PostDO;
import cn.iocoder.yudao.module.system.dal.dataobject.oauth2.OAuth2AccessTokenDO;
import cn.iocoder.yudao.module.system.dal.dataobject.oauth2.OAuth2ApproveDO;
import cn.iocoder.yudao.module.system.dal.dataobject.oauth2.OAuth2ClientDO;
import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.yudao.module.system.util.oauth2.OAuth2Utils;
import org.mapstruct.Mapper;
import org.mapstruct.factory.Mappers;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@Mapper
public interface OAuth2OpenConvert {
@ -44,6 +52,19 @@ public interface OAuth2OpenConvert {
OAuth2OpenUserInfoRespVO.Dept convert(DeptDO dept);
List<OAuth2OpenUserInfoRespVO.Post> convertList(List<PostDO> list);
UserProfileUpdateReqVO convert(UserProfileUpdateReqVO bean);
UserProfileUpdateReqVO convert(OAuth2OpenUserUpdateReqVO bean);
default OAuth2OpenAuthorizeInfoRespVO convert(OAuth2ClientDO client, List<OAuth2ApproveDO> approves) {
// 构建 scopes
List<KeyValue<String, Boolean>> scopes = new ArrayList<>(client.getScopes().size());
Map<String, OAuth2ApproveDO> approveMap = CollectionUtils.convertMap(approves, OAuth2ApproveDO::getScope);
client.getScopes().forEach(scope -> {
OAuth2ApproveDO approve = approveMap.get(scope);
scopes.add(new KeyValue<>(scope, approve != null ? approve.getApproved() : false));
});
// 拼接返回
return new OAuth2OpenAuthorizeInfoRespVO(
new OAuth2OpenAuthorizeInfoRespVO.Client(client.getName(), client.getLogo()), scopes);
}
}

View File

@ -13,7 +13,7 @@ import java.util.Date;
/**
* OAuth2 DO
*
* authorize.vue scope
* sso.vue scope
*
* @author
*/

View File

@ -181,7 +181,7 @@ public class OAuth2ClientServiceImpl implements OAuth2ClientService {
// 校验客户端存在、且开启
OAuth2ClientDO client = clientCache.get(clientId);
if (client == null) {
throw exception(OAUTH2_CLIENT_EXISTS);
throw exception(OAUTH2_CLIENT_NOT_EXISTS);
}
if (ObjectUtil.notEqual(client.getStatus(), CommonStatusEnum.ENABLE.getStatus())) {
throw exception(OAUTH2_CLIENT_DISABLE);

View File

@ -111,25 +111,37 @@ export function refreshToken() {
}
// ========== OAUTH 2.0 相关 ==========
export function authorize() {
export function getAuthorize(clientId) {
return request({
url: '/system/oauth2/authorize?clientId=' + clientId,
method: 'get'
})
}
export function authorize(responseType, clientId, redirectUri, state,
autoApprove, checkedScopes, uncheckedScopes) {
// 构建 scopes
const scopes = {};
for (const scope of checkedScopes) {
scopes[scope] = true;
}
for (const scope of uncheckedScopes) {
scopes[scope] = false;
}
// 发起请求
return service({
url: '/system/oauth2/authorize',
headers:{
'Content-type': 'application/x-www-form-urlencoded',
"Access-Control-Allow-Origin": "*"
},
params: {
response_type: 'code',
client_id: 'test',
redirect_uri: 'https://www.iocoder.cn',
// scopes: {
// read: true,
// write: false
// }
scope: {
read: true,
write: false
}
response_type: responseType,
client_id: clientId,
redirect_uri: redirectUri,
state: state,
auto_approve: autoApprove,
scope: JSON.stringify(scopes)
},
method: 'post'
})

View File

@ -43,8 +43,8 @@ export const constantRoutes = [
hidden: true
},
{
path: '/authorize',
component: (resolve) => require(['@/views/authorize'], resolve),
path: '/sso',
component: (resolve) => require(['@/views/sso'], resolve),
hidden: true
},
{

View File

@ -14,7 +14,7 @@
<!-- 表单 -->
<div class="form-cont">
<el-tabs class="form" style=" float:none;">
<el-tabs class="form" style=" float:none;" value="uname">
<el-tab-pane label="三方授权" name="uname">
</el-tab-pane>
</el-tabs>
@ -53,7 +53,7 @@
<span v-if="!loading"></span>
<span v-else> ...</span>
</el-button>
<el-button size="medium" style="width:37%">拒绝</el-button>
<el-button size="medium" style="width:36%">拒绝</el-button>
</el-form-item>
</el-form>
</div>
@ -69,10 +69,9 @@
<script>
import {getTenantIdByName} from "@/api/system/tenant";
import Cookies from "js-cookie";
import {SystemUserSocialTypeEnum} from "@/utils/constants";
import {getTenantEnable} from "@/utils/ruoyi";
import {authorize} from "@/api/login";
import {authorize, getAuthorize} from "@/api/login";
import {getTenantName, setTenantId} from "@/utils/auth";
export default {
name: "Login",
@ -82,6 +81,18 @@ export default {
loginForm: {
tenantName: "芋道源码",
},
params: { // URL client_idscope
responseType: undefined,
clientId: undefined,
redirectUri: undefined,
state: undefined,
scopes: [], // query
},
client: { //
name: '',
logo: '',
},
checkedScopes: [], // scope
LoginRules: {
tenantName: [
{required: true, trigger: "blur", message: "租户不能为空"},
@ -92,7 +103,7 @@ export default {
const tenantId = res.data;
if (tenantId && tenantId >= 0) {
//
Cookies.set("tenantId", tenantId);
setTenantId(tenantId)
callback();
} else {
callback('租户不存在');
@ -104,44 +115,84 @@ export default {
]
},
loading: false,
redirect: undefined,
//
SysUserSocialTypeEnum: SystemUserSocialTypeEnum,
//
};
},
created() {
//
this.tenantEnable = getTenantEnable();
//
this.redirect = this.$route.query.redirect;
this.getCookie();
//
// client_id=default&redirect_uri=https%3A%2F%2Fwww.iocoder.cn&response_type=code&scope=user.read%20user.write
// client_id=default&redirect_uri=https%3A%2F%2Fwww.iocoder.cn&response_type=code&scope=user.read
this.params.responseType = this.$route.query.response_type
this.params.clientId = this.$route.query.client_id
this.params.redirectUri = this.$route.query.redirect_uri
this.params.state = this.$route.query.state
if (this.$route.query.scope) {
this.params.scopes = this.$route.query.scope.split(' ')
}
// scope
if (this.params.scopes.length > 0) {
this.doAuthorize(true, this.params.scopes, []).then(res => {
const href = res.data
if (!href) {
console.log('自动授权未通过!')
return;
}
location.href = href
})
}
//
getAuthorize(this.params.clientId).then(res => {
this.client = res.data.client
// scope
let scopes
// 1.1 params.scope scopes
if (this.params.scopes.length > 0) {
scopes = []
for (const scope of res.data.scopes) {
if (this.params.scopes.indexOf(scope.key) >= 0) {
scopes.push(scope)
}
}
// 1.2 params.scope 使 scopes
} else {
scopes = res.data.scopes
for (const scope of scopes) {
this.params.scopes.push(scope.key)
}
}
// checkedScopes
for (const scope of scopes) {
if (scope.value) {
this.checkedScopes.push(scope.key)
}
}
})
},
methods: {
getCookie() {
const tenantName = Cookies.get('tenantName');
const tenantName = getTenantName();
this.loginForm = {
tenantName: tenantName === undefined ? this.loginForm.tenantName : tenantName
tenantName: tenantName ? tenantName : this.loginForm.tenantName,
};
},
handleLogin() {
if (true) {
authorize()
return;
}
this.$refs.loginForm.validate(valid => {
if (valid) {
this.loading = true;
//
console.log("发起登录", this.loginForm);
this.$store.dispatch(this.loginForm.loginType === "sms" ? "SmsLogin" : "Login", this.loginForm).then(() => {
this.$router.push({path: this.redirect || "/"}).catch(() => {
});
}).catch(() => {
this.loading = false;
this.getCode();
});
if (!valid) {
return
}
});
})
},
doAuthorize(autoApprove, checkedScopes, uncheckedScopes) {
return authorize(this.params.responseType, this.params.clientId, this.params.redirectUri, this.params.state,
autoApprove, checkedScopes, uncheckedScopes)
}
}
};