Commit 68dd0cdd authored by 董天德's avatar 董天德

Merge remote-tracking branch 'origin/dev_20230205_mq'

parents a392511e 0ff5381a
package com.hungraim.ltc.controller;
import com.hungraim.ltc.util.CsoftSecurityUtil;
import com.hungraim.ltc.util.Result;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.Principal;
import java.util.Map;
......@@ -19,17 +25,38 @@ import java.util.Map;
@RequestMapping("/oauth")
@AllArgsConstructor
public class AuthController {
private final TokenEndpoint tokenEndpoint;
@PostMapping("/token")
@SneakyThrows
public Result<OAuth2AccessToken> postAccessToken(Principal principal, @RequestParam Map<String, String> parameters) {
String password = parameters.get("password");
String decrypt = CsoftSecurityUtil.decryptRSADefault(password);
parameters.put("password", decrypt);
OAuth2AccessToken oAuth2AccessToken = tokenEndpoint.postAccessToken(principal, parameters).getBody();
return Result.success(oAuth2AccessToken);
}
/**
* 获取公钥
* @return
*/
@GetMapping("/genKeyPair")
public Result<String> genKeyPair() {
Map keyMap = CsoftSecurityUtil.createKeyPairs();
return Result.success(keyMap.get(0).toString());
}
@GetMapping("/authLogout")
public Result authLogout(HttpServletRequest request, HttpServletResponse response) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
//清除认证
if (auth != null) {
new SecurityContextLogoutHandler().logout(request, response, auth);
}
return Result.success();
}
}
package com.hungraim.ltc.controller;
import com.hungraim.ltc.util.CsoftSecurityUtil;
import com.hungraim.ltc.util.Result;
import com.nimbusds.jose.jwk.JWKSet;
import com.nimbusds.jose.jwk.RSAKey;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.KeyPair;
import java.security.interfaces.RSAPublicKey;
import java.util.Map;
......
......@@ -58,7 +58,11 @@ public class AuthorizationServerConfiguration extends AuthorizationServerConfigu
this.userDetailsService = userDetailsService;
}
/**
* 配置客户信息(jdbc方式获取用户信息)
* @param clients
* @throws Exception
*/
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.withClientDetails(clientDetails());
......@@ -78,6 +82,7 @@ public class AuthorizationServerConfiguration extends AuthorizationServerConfigu
*/
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
//令牌增强器
TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
List<TokenEnhancer> tokenEnhancers = new ArrayList<>();
tokenEnhancers.add(tokenEnhancer());
......@@ -85,22 +90,26 @@ public class AuthorizationServerConfiguration extends AuthorizationServerConfigu
tokenEnhancerChain.setTokenEnhancers(tokenEnhancers);
endpoints
.authenticationManager(authenticationManager)
.authenticationManager(authenticationManager) //认证管理器(认证账号密码是否正确)
.accessTokenConverter(jwtAccessTokenConverter())
.tokenEnhancer(tokenEnhancerChain)
.userDetailsService(userDetailsService)
.userDetailsService(userDetailsService)//密码模式的用户信息管理
// refresh token有两种使用方式:重复使用(true)、非重复使用(false),默认为true
// 1 重复使用:access token过期刷新时, refresh token过期时间未改变,仍以初次生成的时间为准
// 2 非重复使用:access token过期刷新时, refresh token过期时间延续,在refresh token有效期内刷新便永不失效达到无需再次登录的目的
.reuseRefreshTokens(true);
}
/**
* 令牌端点的安全约束
* @param security
*/
@Override
public void configure(AuthorizationServerSecurityConfigurer security) {
security.authenticationEntryPoint(authenticationEntryPoint()).passwordEncoder(new BCryptPasswordEncoder())
.tokenKeyAccess("isAuthenticated()")
.tokenKeyAccess("isAuthenticated()") //
.checkTokenAccess("permitAll()")
.allowFormAuthenticationForClients();
.allowFormAuthenticationForClients();//表达认证,申请令牌
}
......
......@@ -5,11 +5,14 @@ import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
/**
......@@ -17,18 +20,28 @@ import org.springframework.security.crypto.password.PasswordEncoder;
*/
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true,securedEnabled = true)
@Order(1)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
/**
* 配置用户的安全拦截策略
* @param http
* @throws Exception
*/
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable() //关闭csrf保护
.authorizeRequests().requestMatchers(EndpointRequest.toAnyEndpoint()).permitAll()
.and()
.authorizeRequests()
.antMatchers("/getPublicKey","/oauth/logout").permitAll()
.anyRequest().authenticated();
.antMatchers("/getPublicKey","/oauth/*").permitAll()
.anyRequest().authenticated()
.and()
.logout()
.logoutUrl("/oauth/logout")
.invalidateHttpSession(true);
}
/**
......@@ -40,6 +53,10 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
return super.authenticationManagerBean();
}
/**
* 密码加密器
* @return
*/
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
......
package com.hungraim.ltc.util;
import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
/**
* @Description: 中研通用加密工具 RSA+ASE+SHA256(非对称加密(对称秘钥),对称加密数据,Sha256消息摘要,RSA签名)
* @author wh.huang DateTime 2018年11月15日 下午3:00:21
* @version 1.0
*/
@Slf4j
public class CsoftSecurityUtil {
private static Map<Integer, String> keyMap = new HashMap<>(); // 用于封装随机产生的公钥与私钥
// 加密数据和秘钥的编码方式
public static final String UTF_8 = "UTF-8";
// 填充方式
public static final String AES_ALGORITHM = "AES/CFB/PKCS5Padding";
public static final String RSA_ALGORITHM = "RSA/ECB/PKCS1Padding";
public static final String RSA_ALGORITHM_NOPADDING = "RSA";
/**
* Description: 解密接收数据
* @author wh.huang DateTime 2018年11月15日 下午5:06:42
* @param externalPublicKey
* @param selfPrivateKey
* @param
* @throws InvalidKeyException
* @throws NoSuchPaddingException
* @throws NoSuchAlgorithmException
* @throws BadPaddingException
* @throws IllegalBlockSizeException
* @throws UnsupportedEncodingException
* @throws InvalidAlgorithmParameterException
* @throws DecoderException
*/
public static String decryptReceivedData(PublicKey externalPublicKey, PrivateKey selfPrivateKey, String receiveData) throws InvalidKeyException, NoSuchPaddingException, NoSuchAlgorithmException, BadPaddingException, IllegalBlockSizeException, UnsupportedEncodingException, InvalidAlgorithmParameterException, DecoderException {
@SuppressWarnings("unchecked")
Map<String, String> receivedMap = (Map<String, String>) JSON.parse(receiveData);
// receivedMap为请求方通过from urlencoded方式,请求过来的参数列表
String inputSign = receivedMap.get("sign");
// 用请求方提供的公钥验签,能配对sign,说明来源正确
inputSign = decryptRSA(externalPublicKey, inputSign);
// 校验sign是否一致
String sign = sha256(receivedMap);
if (!sign.equals(inputSign)) {
// sign校验不通过,说明双方发送出的数据和对方收到的数据不一致
System.out.println("input sign: " + inputSign + ", calculated sign: " + sign);
return null;
}
// 解密请求方在发送请求时,加密data字段所用的对称加密密钥
String key = receivedMap.get("key");
String salt = receivedMap.get("salt");
key = decryptRSA(selfPrivateKey, key);
salt = decryptRSA(selfPrivateKey, salt);
// 解密data数据
String data = decryptAES(key, salt, receivedMap.get("data"));
System.out.println("接收到的data内容:" + data);
return data;
}
/**
* Description: 加密数据组织示例
* @author wh.huang DateTime 2018年11月15日 下午5:20:11
* @param externalPublicKey
* @param selfPrivateKey
* @return 加密后的待发送数据
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
* @throws InvalidKeyException
* @throws NoSuchPaddingException
* @throws UnsupportedEncodingException
* @throws BadPaddingException
* @throws IllegalBlockSizeException
* @throws InvalidAlgorithmParameterException
*/
public static String encryptSendData(PublicKey externalPublicKey, PrivateKey selfPrivateKey,JSONObject sendData) throws NoSuchAlgorithmException, InvalidKeySpecException,
InvalidKeyException, NoSuchPaddingException, UnsupportedEncodingException, BadPaddingException,
IllegalBlockSizeException, InvalidAlgorithmParameterException {
// 随机生成对称加密的密钥和IV (IV就是加盐的概念,加密的偏移量)
String aesKeyWithBase64 = genRandomAesSecretKey();
String aesIVWithBase64 = genRandomIV();
// 用接收方提供的公钥加密key和salt,接收方会用对应的私钥解密
String key = encryptRSA(externalPublicKey, aesKeyWithBase64);
String salt = encryptRSA(externalPublicKey, aesIVWithBase64);
// 组织业务数据信息,并用上面生成的对称加密的密钥和IV进行加密
System.out.println("发送的data内容:" + sendData.toJSONString());
String cipherData = encryptAES(aesKeyWithBase64, aesIVWithBase64, sendData.toJSONString());
// 组织请求的key、value对
Map<String, String> requestMap = new TreeMap<String, String>();
requestMap.put("key", key);
requestMap.put("salt", salt);
requestMap.put("data", cipherData);
requestMap.put("source", "由接收方提供"); // 添加来源标识
// 计算sign,并用请求方的私钥加签,接收方会用请求方发放的公钥验签
String sign = sha256(requestMap);
requestMap.put("sign", encryptRSA(selfPrivateKey, sign));
// TODO: 以form urlencoded方式调用,参数为上面组织出来的requestMap
// 注意:请务必以form urlencoded方式,否则base64转码后的个别字符可能会被转成空格,对方接收后将无法正常处理
JSONObject json = new JSONObject();
json.putAll(requestMap);
return json.toString();
}
/**
* Description: 获取随机的对称加密的密钥
* @author wh.huang DateTime 2018年11月15日 下午5:25:53
* @return 对称秘钥字符
* @throws NoSuchAlgorithmException
* @throws UnsupportedEncodingException
* @throws IllegalBlockSizeException
* @throws BadPaddingException
* @throws InvalidKeyException
* @throws NoSuchPaddingException
*/
private static String genRandomAesSecretKey() throws NoSuchAlgorithmException, UnsupportedEncodingException,
IllegalBlockSizeException, BadPaddingException, InvalidKeyException, NoSuchPaddingException {
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(128);
SecretKey secretKey = keyGen.generateKey();
String keyWithBase64 = Base64.encodeBase64(secretKey.getEncoded()).toString();
return keyWithBase64;
}
private static String genRandomIV() {
SecureRandom r = new SecureRandom();
byte[] iv = new byte[16];
r.nextBytes(iv);
String ivParam = Base64.encodeBase64(iv)+"";
return ivParam;
}
/**
* 对称加密数据
*
* @param keyWithBase64
* @param
* @param plainText
* @return
* @throws NoSuchAlgorithmException
* @throws NoSuchPaddingException
* @throws InvalidKeyException
* @throws IllegalBlockSizeException
* @throws BadPaddingException
* @throws UnsupportedEncodingException
* @throws InvalidAlgorithmParameterException
*/
private static String encryptAES(String keyWithBase64, String ivWithBase64, String plainText)
throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException,
BadPaddingException, UnsupportedEncodingException, InvalidAlgorithmParameterException {
byte[] keyWithBase64Arry = keyWithBase64.getBytes();
byte[] ivWithBase64Arry = ivWithBase64.getBytes();
SecretKeySpec key = new SecretKeySpec(Base64.decodeBase64(keyWithBase64Arry), "AES");
IvParameterSpec iv = new IvParameterSpec(Base64.decodeBase64(ivWithBase64Arry));
Cipher cipher = Cipher.getInstance(AES_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, key, iv);
return Base64.encodeBase64(cipher.doFinal(plainText.getBytes(UTF_8))).toString();
}
/**
* 对称解密数据
*
* @param keyWithBase64
* @param cipherText
* @return
* @throws NoSuchAlgorithmException
* @throws NoSuchPaddingException
* @throws InvalidKeyException
* @throws IllegalBlockSizeException
* @throws BadPaddingException
* @throws UnsupportedEncodingException
* @throws InvalidAlgorithmParameterException
*/
private static String decryptAES(String keyWithBase64, String ivWithBase64, String cipherText)
throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException,
BadPaddingException, UnsupportedEncodingException, InvalidAlgorithmParameterException {
byte[] keyWithBase64Arry = keyWithBase64.getBytes();
byte[] ivWithBase64Arry = ivWithBase64.getBytes();
byte[] cipherTextArry = cipherText.getBytes();
SecretKeySpec key = new SecretKeySpec(Base64.decodeBase64(keyWithBase64Arry), "AES");
IvParameterSpec iv = new IvParameterSpec(Base64.decodeBase64(ivWithBase64Arry));
Cipher cipher = Cipher.getInstance(AES_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, key, iv);
return new String(cipher.doFinal(Base64.decodeBase64(cipherTextArry)), UTF_8);
}
/**
* 非对称加密,根据公钥和原始内容产生加密内容
*
* @param key
* @param
* @return
* @throws NoSuchPaddingException
* @throws NoSuchAlgorithmException
* @throws InvalidKeyException
* @throws UnsupportedEncodingException
* @throws BadPaddingException
* @throws IllegalBlockSizeException
* @throws InvalidAlgorithmParameterException
*/
private static String encryptRSA(Key key, String plainText)
throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException,
BadPaddingException, IllegalBlockSizeException, InvalidAlgorithmParameterException {
Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, key);
return Base64.encodeBase64(cipher.doFinal(plainText.getBytes(UTF_8))).toString();
}
/**
* 根据私钥和加密内容产生原始内容
* @param key
* @param content
* @return
* @throws NoSuchPaddingException
* @throws NoSuchAlgorithmException
* @throws InvalidKeyException
* @throws DecoderException
* @throws BadPaddingException
* @throws IllegalBlockSizeException
* @throws UnsupportedEncodingException
* @throws InvalidAlgorithmParameterException
*/
private static String decryptRSA(Key key, String content) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, DecoderException, BadPaddingException, IllegalBlockSizeException, UnsupportedEncodingException, InvalidAlgorithmParameterException {
Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] contentArry = content.getBytes();
return new String(cipher.doFinal(Base64.decodeBase64(contentArry)), UTF_8);
}
/**
* 计算sha256值
*
* @param paramMap
* @return 签名后的所有数据,原始数据+签名
*/
private static String sha256(Map<String, String> paramMap) {
Map<String, String> params = new TreeMap<String, String>(paramMap);
StringBuilder concatStr = new StringBuilder();
for (Entry<String, String> entry : params.entrySet()) {
if ("sign".equals(entry.getKey())) {
continue;
}
concatStr.append(entry.getKey() + "=" + entry.getValue() + "&");
}
return DigestUtils.md5Hex(concatStr.toString());
}
/**
* 创建RSA的公钥和私钥示例 将生成的公钥和私钥用Base64编码后打印出来
* @throws NoSuchAlgorithmException
*/
public static Map createKeyPairs() {
try {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
//公钥
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
//私钥
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
String publicKeyString = new String(Base64.encodeBase64(publicKey.getEncoded()));
String privateKeyString = new String(Base64.encodeBase64((privateKey.getEncoded())));
keyMap.put(0, publicKeyString); //0表示公钥
keyMap.put(1, privateKeyString); //1表示私钥
}catch (NoSuchAlgorithmException e){
e.printStackTrace();
}
return keyMap;
}
/**
* Description:默认的RSA解密方法 一般用来解密 参数 小数据
* @author wh.huang DateTime 2018年12月14日 下午3:43:11
* @param
* @param data
* @return
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
* @throws NoSuchPaddingException
* @throws InvalidKeyException
* @throws IllegalBlockSizeException
* @throws BadPaddingException
*/
public static String decryptRSADefault(String data) throws InvalidKeySpecException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM_NOPADDING);
byte[] privateKeyArray = keyMap.get(1).getBytes();
byte[] dataArray = data.getBytes();
PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKeyArray));
PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
Cipher cipher = Cipher.getInstance(RSA_ALGORITHM_NOPADDING);
cipher.init(Cipher.DECRYPT_MODE, privateKey);
return new String(cipher.doFinal(Base64.decodeBase64(dataArray)), UTF_8);
}
}
\ No newline at end of file
......@@ -51,7 +51,7 @@ public class ResourceServerConfig {
http.oauth2ResourceServer().jwt()
.jwtAuthenticationConverter(jwtAuthenticationConverter());
http.authorizeExchange()
.pathMatchers("/api/oauth/token", "/oauth/token").permitAll()
.pathMatchers("/api/oauth/token","/oauth/*","/api/oauth/genKeyPair").permitAll()
.anyExchange().access(authorizationManager)
.and()
.exceptionHandling()
......
......@@ -64,40 +64,40 @@ public class AuthorizationManager implements ReactiveAuthorizationManager<Author
}
// // 从缓存取资源权限角色关系列表
// Map<Object, Object> permissionRoles = redisTemplate.opsForHash().entries(AuthConstants.PERMISSION_ROLES_KEY);
// Iterator<Object> iterator = permissionRoles.keySet().iterator();
// // 请求路径匹配到的资源需要的角色权限集合authorities统计
// Set<String> authorities = new HashSet<>();
// while (iterator.hasNext()) {
// String pattern = (String) iterator.next();
// if (pathMatcher.match(pattern, path)) {
// authorities.addAll(Convert.toList(String.class, permissionRoles.get(pattern)));
// }
// }
// log.info("require authorities:{}", authorities);
// 从缓存取资源权限角色关系列表
Map<Object, Object> permissionRoles = redisTemplate.opsForHash().entries(AuthConstants.PERMISSION_ROLES_KEY);
Iterator<Object> iterator = permissionRoles.keySet().iterator();
// 请求路径匹配到的资源需要的角色权限集合authorities统计
Set<String> authorities = new HashSet<>();
while (iterator.hasNext()) {
String pattern = (String) iterator.next();
if (pathMatcher.match(pattern, path)) {
authorities.addAll(Convert.toList(String.class, permissionRoles.get(pattern)));
}
}
log.info("require authorities:{}", authorities);
//认证通过且角色匹配的用户可访问当前路径
return mono.map(auth -> {
return new AuthorizationDecision(true);
}).defaultIfEmpty(new AuthorizationDecision(false));
// 认证通过且角色匹配的用户可访问当前路径
// return mono.map(auth -> {
// return new AuthorizationDecision(true);
// }).defaultIfEmpty(new AuthorizationDecision(false));
// return mono
// .filter(Authentication::isAuthenticated)
// .flatMapIterable(Authentication::getAuthorities)
// .map(GrantedAuthority::getAuthority)
// .any(roleId -> {
// // roleId是请求用户的角色(格式:ROLE_{roleId}),authorities是请求资源所需要角色的集合
// log.info("访问路径:{}", path);
// log.info("用户角色信息:{}", roleId);
// log.info("资源需要权限authorities:{}", authorities);
// //如果是管理员 直接放行
// if ("ROLE_0".equals(roleId)) {
// return true;
// }
// return authorities.contains(roleId);
// })
// .map(AuthorizationDecision::new)
// .defaultIfEmpty(new AuthorizationDecision(false));
return mono
.filter(Authentication::isAuthenticated)
.flatMapIterable(Authentication::getAuthorities)
.map(GrantedAuthority::getAuthority)
.any(roleId -> {
// roleId是请求用户的角色(格式:ROLE_{roleId}),authorities是请求资源所需要角色的集合
log.info("访问路径:{}", path);
log.info("用户角色信息:{}", roleId);
log.info("资源需要权限authorities:{}", authorities);
//如果是管理员 直接放行
if ("ROLE_0".equals(roleId)) {
return true;
}
return authorities.contains(roleId);
})
.map(AuthorizationDecision::new)
.defaultIfEmpty(new AuthorizationDecision(false));
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment