提交 546c5d8c 编写于 作者: zhouweidong's avatar zhouweidong

Token秘钥

上级 a18108ad
...@@ -121,6 +121,7 @@ public class apiSecurityConfig extends WebSecurityConfigurerAdapter { ...@@ -121,6 +121,7 @@ public class apiSecurityConfig extends WebSecurityConfigurerAdapter {
.antMatchers("/syspssystems/save").permitAll() .antMatchers("/syspssystems/save").permitAll()
.antMatchers("/uaa/login").permitAll() .antMatchers("/uaa/login").permitAll()
.antMatchers("/uaa/loginbyusername").permitAll() .antMatchers("/uaa/loginbyusername").permitAll()
.antMatchers("/uaa/publickey").permitAll()
// 所有请求都需要认证 // 所有请求都需要认证
.anyRequest().authenticated() .anyRequest().authenticated()
// 防止iframe 造成跨域 // 防止iframe 造成跨域
......
...@@ -3,12 +3,8 @@ package cn.ibizlab.api.rest.extensions; ...@@ -3,12 +3,8 @@ package cn.ibizlab.api.rest.extensions;
import cn.ibizlab.core.uaa.extensions.service.SysAppService; import cn.ibizlab.core.uaa.extensions.service.SysAppService;
import cn.ibizlab.core.uaa.extensions.service.UAACoreService; import cn.ibizlab.core.uaa.extensions.service.UAACoreService;
import cn.ibizlab.util.client.IBZOUFeignClient;
import cn.ibizlab.util.helper.CachedBeanCopier; import cn.ibizlab.util.helper.CachedBeanCopier;
import cn.ibizlab.util.security.AuthTokenUtil; import cn.ibizlab.util.security.*;
import cn.ibizlab.util.security.AuthenticationInfo;
import cn.ibizlab.util.security.AuthenticationUser;
import cn.ibizlab.util.security.AuthorizationLogin;
import cn.ibizlab.util.service.AuthenticationUserService; import cn.ibizlab.util.service.AuthenticationUserService;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
...@@ -16,16 +12,9 @@ import org.springframework.beans.factory.annotation.Qualifier; ...@@ -16,16 +12,9 @@ import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated; import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
/** /**
* 客户端登录认证 * 客户端登录认证
*/ */
...@@ -51,7 +40,8 @@ public class ClientAuthenticationResource ...@@ -51,7 +40,8 @@ public class ClientAuthenticationResource
@Qualifier("UAAUserService") @Qualifier("UAAUserService")
private AuthenticationUserService userDetailsService; private AuthenticationUserService userDetailsService;
@Autowired
UAACoreService uaaCoreService;
@PostMapping(value = "v7/login") @PostMapping(value = "v7/login")
public ResponseEntity<AuthenticationInfo> login(@Validated @RequestBody AuthorizationLogin authorizationLogin){ public ResponseEntity<AuthenticationInfo> login(@Validated @RequestBody AuthorizationLogin authorizationLogin){
...@@ -83,4 +73,9 @@ public class ClientAuthenticationResource ...@@ -83,4 +73,9 @@ public class ClientAuthenticationResource
} }
@GetMapping(value = "uaa/publickey")
public ResponseEntity<String> getPublicKey(){
return ResponseEntity.ok().body(uaaCoreService.getPublicKey());
}
} }
...@@ -9,8 +9,7 @@ import org.springframework.beans.factory.annotation.Value; ...@@ -9,8 +9,7 @@ import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails; 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.io.Serializable;
import java.util.Date; import java.util.Date;
import java.util.HashMap; import java.util.HashMap;
...@@ -18,8 +17,8 @@ import java.util.Map; ...@@ -18,8 +17,8 @@ import java.util.Map;
import java.util.Optional; import java.util.Optional;
import java.util.function.Function; import java.util.function.Function;
@Component //@Component
@ConditionalOnExpression("(!${ibiz.enablePermissionValid:false})&&'${ibiz.auth.service:SimpleTokenUtil}'.equals('SimpleTokenUtil')") //@ConditionalOnExpression("(!${ibiz.enablePermissionValid:false})&&'${ibiz.auth.service:SimpleTokenUtil}'.equals('SimpleTokenUtil')")
public class SimpleTokenUtil implements AuthTokenUtil,Serializable { public class SimpleTokenUtil implements AuthTokenUtil,Serializable {
private static final long serialVersionUID = -3301605591108950415L; private static final long serialVersionUID = -3301605591108950415L;
......
...@@ -6,12 +6,9 @@ import io.jsonwebtoken.Jwts; ...@@ -6,12 +6,9 @@ import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm; import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.impl.DefaultClock; import io.jsonwebtoken.impl.DefaultClock;
import lombok.SneakyThrows; import lombok.SneakyThrows;
import cn.ibizlab.util.client.IBZUAAFeignClient;
import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.IOUtils; import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import java.io.File; import java.io.File;
...@@ -30,12 +27,12 @@ import java.util.Map; ...@@ -30,12 +27,12 @@ import java.util.Map;
import java.util.function.Function; import java.util.function.Function;
@Component @Component
@ConditionalOnExpression("${ibiz.enablePermissionValid:false}||'${ibiz.auth.service:SimpleTokenUtil}'.equals('UAATokenUtil')") //@ConditionalOnExpression("${ibiz.enablePermissionValid:false}||'${ibiz.auth.service:SimpleTokenUtil}'.equals('UAATokenUtil')")
public class UAATokenUtil implements AuthTokenUtil, Serializable { public class UAATokenUtil implements AuthTokenUtil, Serializable {
private static final long serialVersionUID = -3301605591108950415L; private static final long serialVersionUID = -3301605591108950415L;
private Clock clock = DefaultClock.INSTANCE; private Clock clock = DefaultClock.INSTANCE;
@Value("${ibiz.jwt.secret:ibzsecret}") @Value("${ibiz.jwt.secret:ibzsecret}")
private String secret; private String secret;
...@@ -45,10 +42,6 @@ public class UAATokenUtil implements AuthTokenUtil, Serializable { ...@@ -45,10 +42,6 @@ public class UAATokenUtil implements AuthTokenUtil, Serializable {
@Value("${ibiz.jwt.header:Authorization}") @Value("${ibiz.jwt.header:Authorization}")
private String tokenHeader; private String tokenHeader;
@Autowired
private IBZUAAFeignClient uaaFeignClient;
public String getUsernameFromToken(String token) { public String getUsernameFromToken(String token) {
return getClaimFromToken(token, Claims::getSubject); return getClaimFromToken(token, Claims::getSubject);
} }
...@@ -80,7 +73,21 @@ public class UAATokenUtil implements AuthTokenUtil, Serializable { ...@@ -80,7 +73,21 @@ public class UAATokenUtil implements AuthTokenUtil, Serializable {
} }
public String generateToken(UserDetails userDetails) { public String generateToken(UserDetails userDetails) {
return null; 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.RS256, getPrivateKey(getPrivateKeyString()))
.compact();
} }
public Boolean validateToken(String token, UserDetails userDetails) { public Boolean validateToken(String token, UserDetails userDetails) {
...@@ -89,9 +96,38 @@ public class UAATokenUtil implements AuthTokenUtil, Serializable { ...@@ -89,9 +96,38 @@ public class UAATokenUtil implements AuthTokenUtil, Serializable {
return (!isTokenExpired(token) ); return (!isTokenExpired(token) );
} }
private Date calculateExpirationDate(Date createdDate) {
return new Date(createdDate.getTime() + expiration);
}
@SneakyThrows
private String getPrivateKeyString(){
String key="";
String usrHome = System.getProperty("user.home")+"/.ibzrt";
File priKeyFile=new File(usrHome,"ibzrt_rsa");
if(!priKeyFile.exists())
{
key = IOUtils.toString(this.getClass().getResourceAsStream("/keypair/ibzrt_rsa"));
}
else{
key = IOUtils.toString(new FileInputStream(priKeyFile));
}
return key;
}
@SneakyThrows
private String getPublicKeyString(){ private String getPublicKeyString(){
return uaaFeignClient.getPublicKey(); String key="";
String usrHome = System.getProperty("user.home")+"/.ibzrt";
File pubKeyFile=new File(usrHome,"ibzrt_rsa.pub");
if(!pubKeyFile.exists())
{
key = IOUtils.toString(this.getClass().getResourceAsStream("/keypair/ibzrt_rsa.pub"));
}
else{
key = IOUtils.toString(new FileInputStream(pubKeyFile));
}
return key;
} }
/** /**
...@@ -109,5 +145,17 @@ public class UAATokenUtil implements AuthTokenUtil, Serializable { ...@@ -109,5 +145,17 @@ public class UAATokenUtil implements AuthTokenUtil, Serializable {
return keyFactory.generatePublic(x509EncodedKeySpec); return keyFactory.generatePublic(x509EncodedKeySpec);
} }
/**
* 获取PrivateKey对象
* @param privateKeyBase64
* @return
*/
@SneakyThrows
private PrivateKey getPrivateKey(String privateKeyBase64) {
byte[] byteKey = Base64.decodeBase64(privateKeyBase64);
PKCS8EncodedKeySpec x509EncodedKeySpec = new PKCS8EncodedKeySpec(byteKey);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
return keyFactory.generatePrivate(x509EncodedKeySpec);
}
} }
Markdown 格式
0% or
您添加了 0 到此讨论。请谨慎行事。
先完成此消息的编辑!
想要评论请 注册