提交 626f114c 编写于 作者: ibizdev's avatar ibizdev

ibiz4j 发布系统代码

上级 6798ff9a
## v7.0.0-alpha.9 [2020-6-11]
### Bug修复
数值代码表多语言
树右键菜单滚动条样式bug
列表面板界面行为bug
多选视图界面逻辑修复
图表刷新bug修复
日历部件选中抛出数据逻辑调整
编辑视图,app-span显示0时不显示
树视图右键界面行为刷新bug
快捷菜单控制台报错bug
门户加载自定义模型错误时,正常显示默认看板
修复雷达图显示异常问题
修复编辑类、分页导航视图带数据标题问题
修复饼图、漏斗图 获取序列参数错误问题
### 功能新增及优化
#### 模板
看板和门户布局模板调整,支持门户部件标题栏界面行为组
支持数据选择、地址框、自动完成、下拉列表、标签、选项框列表、单选列表等编辑器导航参数调整
支持树导航栏、表格导航栏、列表导航栏、卡片导航栏、日历导航栏、表单关系界面、数据选择面板、分页导航面板、数据关系栏、界面行为、新建逻辑、编辑逻辑导航参数调整
支持图表无数据时显示暂无数据
支持表格新建默认值
支持日历部件右键菜单
支持表格列触发界面行为
面板布局调整
#### 基础文件
门户部件视图的样式
数据选择,地址框,自动完成,下拉列表,标签,选项框列表,单选列表等编辑器导航参数调整
表单项label位置
调整登录页面
穿梭框编辑器支持
## v7.0.0-alpha.8 [2020-6-4]
### Bug修复
......
......@@ -26,7 +26,7 @@
"element-ui": "^2.13.0",
"file-saver": "^2.0.2",
"font-awesome": "^4.7.0",
"ibiz-gantt-elastic": "^1.0.16",
"ibiz-gantt-elastic": "^1.0.17",
"ibiz-vue-lib": "^0.1.10",
"interactjs": "^1.9.4",
"moment": "^2.24.0",
......
......@@ -28,21 +28,25 @@
<dropdown-menu slot='list' v-if="uiActionGroup.details && Array.isArray(uiActionGroup.details)">
<dropdown-item v-for="(detail,index) in (uiActionGroup.details)" :key="index" :name="detail.name">
<span class='item' @click="doUIAction($event, detail)">
<template v-if="detail.icon && !Object.is(detail.icon, '')">
<i :class="detail.icon" ></i>
</template>
<template v-if="!(detail.icon && !Object.is(detail.icon, ''))">
<div v-if="detail.img && !Object.is(detail.img, '')">
<img :src="detail.img" />
</div>
<template v-if="detail.isShowIcon">
<template v-if="detail.icon && !Object.is(detail.icon, '')">
<i :class="detail.icon" ></i>
</template>
<template v-if="!(detail.icon && !Object.is(detail.icon, ''))">
<div v-if="detail.img && !Object.is(detail.img, '')">
<img :src="detail.img" />
</div>
</template>
</template>
&nbsp;
<span>
<template v-if="uiActionGroup.langbase && !Object.is(uiActionGroup.langbase, '') && detail.uiactiontag && !Object.is(detail.uiactiontag, '')">
{{$t(`${uiActionGroup.langbase}.uiactions.${detail.uiactiontag}`)}}
</template>
<template v-if="!(uiActionGroup.langbase && !Object.is(uiActionGroup.langbase, '') && detail.uiactiontag && !Object.is(detail.uiactiontag, ''))">
{{detail.caption}}
<template v-if="detail.isShowCaption">
<template v-if="uiActionGroup.langbase && !Object.is(uiActionGroup.langbase, '') && detail.uiactiontag && !Object.is(detail.uiactiontag, '')">
{{$t(`${uiActionGroup.langbase}.uiactions.${detail.uiactiontag}`)}}
</template>
<template v-if="!(uiActionGroup.langbase && !Object.is(uiActionGroup.langbase, '') && detail.uiactiontag && !Object.is(detail.uiactiontag, ''))">
{{detail.caption}}
</template>
</template>
</span>
</span>
......@@ -55,21 +59,25 @@
<template v-if="uiActionGroup.details && Array.isArray(uiActionGroup.details)">
<div v-for="(detail,index) in uiActionGroup.details" :key="index">
<span class='item' @click="doUIAction($event, detail)">
<template v-if="detail.icon && !Object.is(detail.icon, '')">
<i :class="detail.icon" ></i>
</template>
<template v-if="!(detail.icon && !Object.is(detail.icon, ''))">
<div v-if="detail.img && !Object.is(detail.img, '')">
<img :src="detail.img" />
</div>
</template>
<template v-if="detail.isShowIcon">
<template v-if="detail.icon && !Object.is(detail.icon, '')">
<i :class="detail.icon" ></i>
</template>
<template v-if="!(detail.icon && !Object.is(detail.icon, ''))">
<div v-if="detail.img && !Object.is(detail.img, '')">
<img :src="detail.img" />
</div>
</template>
</template>
&nbsp;
<span>
<template v-if="uiActionGroup.langbase && !Object.is(uiActionGroup.langbase, '') && detail.uiactiontag && !Object.is(detail.uiactiontag, '')">
{{$t(`${uiActionGroup.langbase}.uiactions.${detail.uiactiontag}`)}}
</template>
<template v-if="!(uiActionGroup.langbase && !Object.is(uiActionGroup.langbase, '') && detail.uiactiontag && !Object.is(detail.uiactiontag, ''))">
{{detail.caption}}
<template v-if="detail.isShowCaption">
<template v-if="uiActionGroup.langbase && !Object.is(uiActionGroup.langbase, '') && detail.uiactiontag && !Object.is(detail.uiactiontag, '')">
{{$t(`${uiActionGroup.langbase}.uiactions.${detail.uiactiontag}`)}}
</template>
<template v-if="!(uiActionGroup.langbase && !Object.is(uiActionGroup.langbase, '') && detail.uiactiontag && !Object.is(detail.uiactiontag, ''))">
{{detail.caption}}
</template>
</template>
</span>
</span>
......
......@@ -16,4 +16,31 @@
display: inline-block;
padding: 0 0 10px;
}
}
.app-form-item-label-left{
.app-form-item-label{
float: left;
text-align: right;
padding-right: 12px;
}
}
.app-form-item-label-right{
.app-form-item-label{
float: right;
text-align: left;
padding-left: 12px;
}
}
.app-form-item-label-top{
.app-form-item-label{
display: block;
padding-bottom: 10px;
}
}
.app-form-item-label-bottom{
.app-form-item-label{
display: block;
padding-top: 10px;
}
}
\ No newline at end of file
......@@ -21,12 +21,16 @@
:error="error"
:required="required"
:rules="rules"
:class="classes"
:label-width="this.isShowCaption ? !Object.is(this.labelPos, 'TOP') ? this.labelWidth : null : 0">
<span slot='label' v-if="this.isShowCaption && this.labelWidth > 0" :class="labelclasses">
{{this.isEmptyCaption ? '' : this.caption}}
</span>
:class="classes">
<div v-if="Object.is(this.labelPos,'BOTTOM') || Object.is(this.labelPos,'NONE') || !this.labelPos" class="slot-editor" :style="slotstyle">
<slot></slot>
</div>
<span v-if="!Object.is(this.labelPos,'NONE') && this.isShowCaption && this.labelWidth > 0" :style="labelstyle" :class="labelclasses">
{{this.isEmptyCaption ? '' : this.caption}}
</span>
<div v-if="Object.is(this.labelPos,'TOP') || Object.is(this.labelPos,'LEFT') || Object.is(this.labelPos,'RIGHT')" class="slot-editor" :style="slotstyle">
<slot></slot>
</div>
</form-item>
</div>
</div>
......@@ -167,9 +171,27 @@ export default class AppFormItem extends Vue {
* @memberof AppFormItem
*/
get classes(): string[] {
let posClass = '';
switch (this.labelPos) {
case 'TOP':
posClass = 'app-form-item-label-top';
break;
case 'LEFT':
posClass = 'app-form-item-label-left';
break;
case 'BOTTOM':
posClass = 'app-form-item-label-bottom';
break;
case 'RIGHT':
posClass = 'app-form-item-label-right';
break;
case 'NONE':
posClass = 'app-form-item-label-none';
break;
}
return [
'app-form-item',
Object.is(this.labelPos, 'TOP') ? 'app-form-item-label-top' : ''
posClass
];
}
......@@ -181,7 +203,33 @@ export default class AppFormItem extends Vue {
* @memberof AppFormItem
*/
get labelclasses():string{
return this.labelStyle?this.labelStyle:'';
return this.labelStyle?this.labelStyle+' app-form-item-label':'app-form-item-label';
}
/**
* label行内样式
*
* @readonly
* @type {string}
* @memberof AppFormItem
*/
get labelstyle():any{
return {width:this.labelWidth+'px'};
}
/**
* slot行内样式
*
* @readonly
* @type {string}
* @memberof AppFormItem
*/
get slotstyle():any{
if(Object.is(this.labelPos,'LEFT')){
return {marginLeft:this.labelWidth+'px'};
}else if(Object.is(this.labelPos,'RIGHT')){
return {marginRight:this.labelWidth+'px'};
}
}
/**
......
.ivu-select-dropdown {
padding: 0px;
.hidden {
display: none;
}
}
\ No newline at end of file
.transfer-select{
.ivu-select-dropdown {
padding: 0px;
.hidden {
display: none;
}
.el-transfer{
min-width: 100% !important;
display: flex;
justify-content: space-between;
.el-transfer-panel{
min-width: 25%;
}
.el-transfer__buttons{
align-self: center;
}
}
}
}
......@@ -116,7 +116,7 @@ export default class DropDownList extends Vue {
* @memberof AppFormDRUIPart
*/
@Prop() public viewparams!: any;
/**
* 是否禁用
* @type {any}
......
......@@ -89,6 +89,7 @@ export default class EditView2Engine extends EditViewEngine {
*/
public onFormLoad(arg: any = {}): void {
super.onFormLoad(arg);
this.view.formData = arg;
if (this.getDRBar()) {
const tag = this.getDRBar().name;
this.setViewState2({ tag: tag, action: 'state', viewdata: this.view.vieparams });
......@@ -103,6 +104,7 @@ export default class EditView2Engine extends EditViewEngine {
*/
public onFormSave(arg: any = {}): void {
super.onFormSave(arg);
this.view.formData = arg;
if (this.getDRBar()) {
const tag = this.getDRBar().name;
this.setViewState2({ tag: tag, action: 'state', viewdata: this.view.viewparams });
......
......@@ -89,6 +89,7 @@ export default class EditView3Engine extends EditViewEngine {
*/
public onFormLoad(arg: any = {}): void {
super.onFormLoad(arg);
this.view.formData = arg;
if (this.getDrTab()) {
const tag = this.getDrTab().name;
this.setViewState2({ tag: tag, action: 'state', viewdata: this.view.viewparams });
......@@ -103,6 +104,7 @@ export default class EditView3Engine extends EditViewEngine {
*/
public onFormSave(arg: any = {}): void {
super.onFormSave(arg);
this.view.formData = arg;
if (this.getDrTab()) {
const tag = this.getDrTab().name;
this.setViewState2({ tag: tag, action: 'state', viewdata: this.view.viewparams });
......
......@@ -44,7 +44,7 @@ export class UIActionTool {
*/
private static formatData(actionTarget: any, args: any,parentContext:any,parentParams:any, _params: any): any {
let _data: any = {};
if (Object.is(actionTarget, 'SINGLEKEY')) {
if (Object.is(actionTarget, 'SINGLEKEY') || Object.is(actionTarget, 'NONE')) {
let [arg] = args;
Object.keys(_params).forEach((name: string) => {
let hasProperty = true;
......
......@@ -128,7 +128,7 @@ export class ViewTool {
const [{ pathName, parameterName }] = parameters;
routePath = `/${pathName}`;
if (Object.keys(data).length > 0) {
routePath = `${routePath}/${qs.stringify(data, { delimiter: ';' })}`;
routePath = `${routePath}?${qs.stringify(data, { delimiter: ';' })}`;
}
} else if (parameters.length === 2) {
let [arg] = args;
......@@ -138,7 +138,7 @@ export class ViewTool {
arg[_parameterName] : null;
routePath = `/${_pathName}/${_value}/${_pathName2}`;
if (Object.keys(data).length > 0) {
routePath = `${routePath}/${qs.stringify(data, { delimiter: ';' })}`;
routePath = `${routePath}?${qs.stringify(data, { delimiter: ';' })}`;
}
}
return routePath;
......
......@@ -5238,10 +5238,10 @@ human-signals@^1.1.1:
resolved "https://registry.yarnpkg.com/human-signals/-/human-signals-1.1.1.tgz#c5b1cd14f50aeae09ab6c59fe63ba3395fe4dfa3"
integrity sha512-SEQu7vl8KjNL2eoGBLF3+wAjpsNfA9XMlXAYj/3EdaNfAlxKthD1xjEQfGOUhllCGGJVNY34bRr6lPINhNjyZw==
ibiz-gantt-elastic@^1.0.16:
version "1.0.16"
resolved "https://registry.npm.taobao.org/ibiz-gantt-elastic/download/ibiz-gantt-elastic-1.0.16.tgz#e2de7e8d4bdb3c292cfbc97c4f970c8ecfe6c43b"
integrity sha1-4t5+jUvbPCks+8l8T5cMjs/mxDs=
ibiz-gantt-elastic@^1.0.17:
version "1.0.17"
resolved "https://registry.yarnpkg.com/ibiz-gantt-elastic/-/ibiz-gantt-elastic-1.0.17.tgz#447cce5db2e0127d2336c20370fc251992520c6f"
integrity sha512-AJOYXZGM020wafn60RJLM2yKmtT2BjCpBKkZ0PONcxdqW/kCyXOqEo3c3/PBtFEkJx/8KGTayB013BOdGI1+uQ==
dependencies:
dayjs "^1.8.16"
resize-observer-polyfill "^1.5.1"
......
......@@ -12,6 +12,10 @@ zuul:
path: /uaa/**
serviceId: ibzuaa-api
stripPrefix: false
config:
path: /config/**
serviceId: ibzuaa-api
stripPrefix: false
oucore:
path: /ibzorganizations/**
serviceId: ibzou-api
......
......@@ -7,6 +7,7 @@ import java.util.Map;
import java.math.BigInteger;
import java.util.HashMap;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
......
......@@ -10,6 +10,10 @@ public class CustomJacksonSerializer<T> extends Jackson2JsonRedisSerializer<T>
public static final String DEFAULT_PACKAGE ="[\\w+\\.]+\\.AuthenticationUser";
public static final String CLASSNAME_EX="_$$_";
public static final String CLASSNAME_EX_PATTEN="(_\\$\\$_)(\\w+)";
public static final String USER_PACKAGE= AuthenticationUser.class.getName();
public CustomJacksonSerializer(Class type) {
......@@ -20,6 +24,12 @@ public class CustomJacksonSerializer<T> extends Jackson2JsonRedisSerializer<T>
public T deserialize(byte[] bytes) throws SerializationException {
String serializerContent = new String(bytes, DEFAULT_CHARSET);
Matcher matcher = Pattern.compile(DEFAULT_PACKAGE).matcher(serializerContent);
return matcher.find()?super.deserialize(serializerContent.replaceAll(DEFAULT_PACKAGE,USER_PACKAGE).getBytes()):super.deserialize(bytes);
if(matcher.find()){
serializerContent=serializerContent.replaceAll(DEFAULT_PACKAGE,USER_PACKAGE);
}
if(serializerContent.contains(CLASSNAME_EX)){
serializerContent=serializerContent.replaceAll(CLASSNAME_EX_PATTEN,"");
}
return super.deserialize(serializerContent.getBytes());
}
}
......@@ -22,4 +22,9 @@ public class IBZUAAFallback implements IBZUAAFeignClient {
public AuthenticationUser loginByUsername(String username) {
return null;
}
@Override
public String getPublicKey() {
return null;
}
}
......@@ -2,6 +2,7 @@ package cn.ibizlab.util.client;
import cn.ibizlab.util.security.AuthenticationUser;
import cn.ibizlab.util.security.AuthorizationLogin;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.*;
import com.alibaba.fastjson.JSONObject;
......@@ -28,4 +29,8 @@ public interface IBZUAAFeignClient
@PostMapping(value = "/uaa/loginbyusername")
AuthenticationUser loginByUsername(@RequestBody String username);
@Cacheable(value="ibzuaa_publickey")
@GetMapping(value = "/uaa/publickey")
String getPublicKey();
}
package cn.ibizlab.util.security;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Clock;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.impl.DefaultClock;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
public interface AuthTokenUtil {
@Component
public class AuthTokenUtil implements Serializable {
String generateToken(UserDetails userDetails);
private static final long serialVersionUID = -3301605591108950415L;
private Clock clock = DefaultClock.INSTANCE;
Boolean validateToken(String token, UserDetails userDetails);
@Value("${ibiz.jwt.secret:ibzsecret}")
private String secret;
String getUsernameFromToken(String token);
@Value("${ibiz.jwt.expiration:7200000}")
private Long expiration;
@Value("${ibiz.jwt.header:Authorization}")
private String tokenHeader;
public String getUsernameFromToken(String token) {
return getClaimFromToken(token, Claims::getSubject);
}
public Date getIssuedAtDateFromToken(String token) {
return getClaimFromToken(token, Claims::getIssuedAt);
}
public Date getExpirationDateFromToken(String token) {
return getClaimFromToken(token, Claims::getExpiration);
}
public <T> T getClaimFromToken(String token, Function<Claims, T> claimsResolver) {
final Claims claims = getAllClaimsFromToken(token);
return claimsResolver.apply(claims);
}
private Claims getAllClaimsFromToken(String token) {
return Jwts.parser()
.setSigningKey(secret)
.parseClaimsJws(token)
.getBody();
}
private Boolean isTokenExpired(String token) {
final Date expiration = getExpirationDateFromToken(token);
return expiration.before(clock.now());
}
private Boolean isCreatedBeforeLastPasswordReset(Date created, Date lastPasswordReset) {
return (lastPasswordReset != null && created.before(lastPasswordReset));
}
private Boolean ignoreTokenExpiration(String token) {
// here you specify tokens, for that the expiration is ignored
return false;
}
public String generateToken(UserDetails userDetails) {
Map<String, Object> claims = new HashMap<>();
return doGenerateToken(claims, userDetails.getUsername());
}
private String doGenerateToken(Map<String, Object> claims, String subject) {
final Date createdDate = clock.now();
final Date expirationDate = calculateExpirationDate(createdDate);
return Jwts.builder()
.setClaims(claims)
.setSubject(subject)
.setIssuedAt(createdDate)
.setExpiration(expirationDate)
.signWith(SignatureAlgorithm.HS512, secret)
.compact();
}
public Boolean canTokenBeRefreshed(String token, Date lastPasswordReset) {
final Date created = getIssuedAtDateFromToken(token);
return !isCreatedBeforeLastPasswordReset(created, lastPasswordReset)
&& (!isTokenExpired(token) || ignoreTokenExpiration(token));
}
public String refreshToken(String token) {
final Date createdDate = clock.now();
final Date expirationDate = calculateExpirationDate(createdDate);
final Claims claims = getAllClaimsFromToken(token);
claims.setIssuedAt(createdDate);
claims.setExpiration(expirationDate);
return Jwts.builder()
.setClaims(claims)
.signWith(SignatureAlgorithm.HS512, secret)
.compact();
}
public Boolean validateToken(String token, UserDetails userDetails) {
AuthenticationUser user = (AuthenticationUser) userDetails;
final Date created = getIssuedAtDateFromToken(token);
return (!isTokenExpired(token) );
}
private Date calculateExpirationDate(Date createdDate) {
return new Date(createdDate.getTime() + expiration);
}
/**
* Get the login of the current user.
*
* @return the login of the current user
*/
public static Optional<String> getCurrentUserLogin() {
SecurityContext securityContext = SecurityContextHolder.getContext();
return Optional.ofNullable(securityContext.getAuthentication())
.map(authentication -> {
if (authentication.getPrincipal() instanceof UserDetails) {
UserDetails springSecurityUser = (UserDetails) authentication.getPrincipal();
return springSecurityUser.getUsername();
} else if (authentication.getPrincipal() instanceof String) {
return (String) authentication.getPrincipal();
}
return null;
});
}
/**
* Check if a user is authenticated.
*
* @return true if the user is authenticated, false otherwise
*/
public static boolean isAuthenticated() {
SecurityContext securityContext = SecurityContextHolder.getContext();
return Optional.ofNullable(securityContext.getAuthentication())
.map(authentication -> authentication.getAuthorities().stream()
.noneMatch(grantedAuthority -> grantedAuthority.getAuthority().equals("ANONYMOUS")))
.orElse(false);
}
/**
* If the current user has a specific authority (security role).
* <p>
* The name of this method comes from the isUserInRole() method in the Servlet API
*
* @param authority the authority to check
* @return true if the current user has the authority, false otherwise
*/
public static boolean isCurrentUserInRole(String authority) {
SecurityContext securityContext = SecurityContextHolder.getContext();
return Optional.ofNullable(securityContext.getAuthentication())
.map(authentication -> authentication.getAuthorities().stream()
.anyMatch(grantedAuthority -> grantedAuthority.getAuthority().equals(authority)))
.orElse(false);
}
}
package cn.ibizlab.util.security;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Clock;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.impl.DefaultClock;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
@Component
@ConditionalOnExpression("(!${ibiz.enablePermissionValid:false})&&'${ibiz.auth.token.util:UAATokenUtil}'.equals('SimpleTokenUtil')")
public class SimpleTokenUtil implements AuthTokenUtil,Serializable {
private static final long serialVersionUID = -3301605591108950415L;
private Clock clock = DefaultClock.INSTANCE;
@Value("${ibiz.jwt.secret:ibzsecret}")
private String secret;
@Value("${ibiz.jwt.expiration:7200000}")
private Long expiration;
@Value("${ibiz.jwt.header:Authorization}")
private String tokenHeader;
public String getUsernameFromToken(String token) {
return getClaimFromToken(token, Claims::getSubject);
}
public Date getIssuedAtDateFromToken(String token) {
return getClaimFromToken(token, Claims::getIssuedAt);
}
public Date getExpirationDateFromToken(String token) {
return getClaimFromToken(token, Claims::getExpiration);
}
public <T> T getClaimFromToken(String token, Function<Claims, T> claimsResolver) {
final Claims claims = getAllClaimsFromToken(token);
return claimsResolver.apply(claims);
}
private Claims getAllClaimsFromToken(String token) {
return Jwts.parser()
.setSigningKey(secret)
.parseClaimsJws(token)
.getBody();
}
private Boolean isTokenExpired(String token) {
final Date expiration = getExpirationDateFromToken(token);
return expiration.before(clock.now());
}
private Boolean isCreatedBeforeLastPasswordReset(Date created, Date lastPasswordReset) {
return (lastPasswordReset != null && created.before(lastPasswordReset));
}
private Boolean ignoreTokenExpiration(String token) {
// here you specify tokens, for that the expiration is ignored
return false;
}
public String generateToken(UserDetails userDetails) {
Map<String, Object> claims = new HashMap<>();
return doGenerateToken(claims, userDetails.getUsername());
}
private String doGenerateToken(Map<String, Object> claims, String subject) {
final Date createdDate = clock.now();
final Date expirationDate = calculateExpirationDate(createdDate);
return Jwts.builder()
.setClaims(claims)
.setSubject(subject)
.setIssuedAt(createdDate)
.setExpiration(expirationDate)
.signWith(SignatureAlgorithm.HS512, secret)
.compact();
}
public Boolean canTokenBeRefreshed(String token, Date lastPasswordReset) {
final Date created = getIssuedAtDateFromToken(token);
return !isCreatedBeforeLastPasswordReset(created, lastPasswordReset)
&& (!isTokenExpired(token) || ignoreTokenExpiration(token));
}
public String refreshToken(String token) {
final Date createdDate = clock.now();
final Date expirationDate = calculateExpirationDate(createdDate);
final Claims claims = getAllClaimsFromToken(token);
claims.setIssuedAt(createdDate);
claims.setExpiration(expirationDate);
return Jwts.builder()
.setClaims(claims)
.signWith(SignatureAlgorithm.HS512, secret)
.compact();
}
public Boolean validateToken(String token, UserDetails userDetails) {
AuthenticationUser user = (AuthenticationUser) userDetails;
final Date created = getIssuedAtDateFromToken(token);
return (!isTokenExpired(token) );
}
private Date calculateExpirationDate(Date createdDate) {
return new Date(createdDate.getTime() + expiration);
}
/**
* Get the login of the current user.
*
* @return the login of the current user
*/
public static Optional<String> getCurrentUserLogin() {
SecurityContext securityContext = SecurityContextHolder.getContext();
return Optional.ofNullable(securityContext.getAuthentication())
.map(authentication -> {
if (authentication.getPrincipal() instanceof UserDetails) {
UserDetails springSecurityUser = (UserDetails) authentication.getPrincipal();
return springSecurityUser.getUsername();
} else if (authentication.getPrincipal() instanceof String) {
return (String) authentication.getPrincipal();
}
return null;
});
}
/**
* Check if a user is authenticated.
*
* @return true if the user is authenticated, false otherwise
*/
public static boolean isAuthenticated() {
SecurityContext securityContext = SecurityContextHolder.getContext();
return Optional.ofNullable(securityContext.getAuthentication())
.map(authentication -> authentication.getAuthorities().stream()
.noneMatch(grantedAuthority -> grantedAuthority.getAuthority().equals("ANONYMOUS")))
.orElse(false);
}
/**
* If the current user has a specific authority (security role).
* <p>
* The name of this method comes from the isUserInRole() method in the Servlet API
*
* @param authority the authority to check
* @return true if the current user has the authority, false otherwise
*/
public static boolean isCurrentUserInRole(String authority) {
SecurityContext securityContext = SecurityContextHolder.getContext();
return Optional.ofNullable(securityContext.getAuthentication())
.map(authentication -> authentication.getAuthorities().stream()
.anyMatch(grantedAuthority -> grantedAuthority.getAuthority().equals(authority)))
.orElse(false);
}
}
package cn.ibizlab.util.security;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Clock;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.impl.DefaultClock;
import lombok.SneakyThrows;
import cn.ibizlab.util.client.IBZUAAFeignClient;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import java.io.File;
import java.io.FileInputStream;
import java.io.Serializable;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
@Component
@ConditionalOnExpression("${ibiz.enablePermissionValid:false}||'${ibiz.auth.token.util:UAATokenUtil}'.equals('UAATokenUtil')")
public class UAATokenUtil implements AuthTokenUtil, Serializable {
private static final long serialVersionUID = -3301605591108950415L;
private Clock clock = DefaultClock.INSTANCE;
@Value("${ibiz.jwt.secret:ibzsecret}")
private String secret;
@Value("${ibiz.jwt.expiration:7200000}")
private Long expiration;
@Value("${ibiz.jwt.header:Authorization}")
private String tokenHeader;
@Autowired
private IBZUAAFeignClient uaaFeignClient;
public String getUsernameFromToken(String token) {
return getClaimFromToken(token, Claims::getSubject);
}
public Date getIssuedAtDateFromToken(String token) {
return getClaimFromToken(token, Claims::getIssuedAt);
}
public Date getExpirationDateFromToken(String token) {
return getClaimFromToken(token, Claims::getExpiration);
}
public <T> T getClaimFromToken(String token, Function<Claims, T> claimsResolver) {
final Claims claims = getAllClaimsFromToken(token);
return claimsResolver.apply(claims);
}
public Claims getAllClaimsFromToken(String token) {
PublicKey publicKey = getPublicKey(getPublicKeyString());
return Jwts.parser()
.setSigningKey(publicKey)
.parseClaimsJws(token)
.getBody();
}
private Boolean isTokenExpired(String token) {
final Date expiration = getExpirationDateFromToken(token);
return expiration.before(clock.now());
}
public String generateToken(UserDetails userDetails) {
return null;
}
public Boolean validateToken(String token, UserDetails userDetails) {
AuthenticationUser user = (AuthenticationUser) userDetails;
final Date created = getIssuedAtDateFromToken(token);
return (!isTokenExpired(token) );
}
private String getPublicKeyString(){
return uaaFeignClient.getPublicKey();
}
/**
* 获取PublicKey对象
* @param publicKeyBase64
* @return
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
*/
@SneakyThrows
public PublicKey getPublicKey(String publicKeyBase64) {
byte[] byteKey = Base64.decodeBase64(publicKeyBase64);
X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(byteKey);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
return keyFactory.generatePublic(x509EncodedKeySpec);
}
}
Markdown 格式
0% or
您添加了 0 到此讨论。请谨慎行事。
先完成此消息的编辑!
想要评论请 注册