Skip to content

打通三方登录&移除shiro #5819

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jan 17, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion db/增量SQL/sas升级脚本.sql
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ now(),
null,
'3eacac0e-0de9-4727-9a64-6bdd4be2ee1f',
'client_secret_basic',
'refresh_token,authorization_code,password',
'refresh_token,authorization_code,password,app,phone,social',
'http://127.0.0.1:8080/jeecg-',
'http://127.0.0.1:8080/',
'*',
Expand Down
76 changes: 0 additions & 76 deletions jeecg-boot-base-core/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -173,63 +173,6 @@
<version>${java-jwt.version}</version>
</dependency>

<!--shiro-->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring-boot-starter</artifactId>
<version>${shiro.version}</version>
<exclusions>
<exclusion>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- shiro-redis -->
<dependency>
<groupId>org.crazycake</groupId>
<artifactId>shiro-redis</artifactId>
<version>${shiro-redis.version}</version>
<exclusions>
<exclusion>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
</exclusion>
<exclusion>
<artifactId>checkstyle</artifactId>
<groupId>com.puppycrawl.tools</groupId>
</exclusion>
<!-- TODO shiro 无法使用 spring boot 3.X 自带的jedis,降版本处理 -->
<exclusion>
<artifactId>jedis</artifactId>
<groupId>redis.clients</groupId>
</exclusion>
</exclusions>
</dependency>
<!-- TODO shiro 无法使用 spring boot 3.X 自带的jedis,降版本处理 -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>

<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<classifier>jakarta</classifier>
<version>${shiro.version}</version>
<!-- 排除仍使用了javax.servlet的依赖 -->
<exclusions>
<exclusion>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-web</artifactId>
</exclusion>
</exclusions>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
Expand All @@ -244,25 +187,6 @@
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-cas</artifactId>
</dependency>
<!-- 引入适配jakarta的依赖包 -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<classifier>jakarta</classifier>
<version>${shiro.version}</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-web</artifactId>
<classifier>jakarta</classifier>
<version>${shiro.version}</version>
<exclusions>
<exclusion>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
</exclusion>
</exclusions>
</dependency>

<!-- knife4j -->
<dependency>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@

import cn.hutool.core.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.UnauthorizedException;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.enums.SentinelErrorInfoEnum;
import org.springframework.dao.DataIntegrityViolationException;
Expand Down Expand Up @@ -87,12 +85,6 @@ public Result<?> handleDuplicateKeyException(DuplicateKeyException e){
return Result.error("数据库中已存在该记录");
}

@ExceptionHandler({UnauthorizedException.class, AuthorizationException.class})
public Result<?> handleAuthorizationException(AuthorizationException e){
log.error(e.getMessage(), e);
return Result.noauth("没有权限,请联系管理员授权");
}

@ExceptionHandler(AccessDeniedException.class)
public Result<?> handleAuthorizationException(AccessDeniedException e){
log.error(e.getMessage(), e);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
import com.baomidou.mybatisplus.extension.service.IService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
package org.jeecg.common.util.encryption;

import org.apache.shiro.codec.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

/**
* @Description: AES 加密
Expand Down Expand Up @@ -49,7 +48,7 @@ public static String encrypt(String data, String key, String iv) throws Exceptio
cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
byte[] encrypted = cipher.doFinal(plaintext);

return Base64.encodeToString(encrypted);
return Base64.getEncoder().encodeToString(encrypted);

} catch (Exception e) {
e.printStackTrace();
Expand All @@ -67,7 +66,7 @@ public static String encrypt(String data, String key, String iv) throws Exceptio
*/
public static String desEncrypt(String data, String key, String iv) throws Exception {
//update-begin-author:taoyan date:2022-5-23 for:VUEN-1084 【vue3】online表单测试发现的新问题 6、解密报错 ---解码失败应该把异常抛出去,在外面处理
byte[] encrypted1 = Base64.decode(data);
byte[] encrypted1 = Base64.getDecoder().decode(data);

Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,6 @@ public class JeecgBaseConfig {
*/
private Firewall firewall;

/**
* shiro拦截排除
*/
private Shiro shiro;
/**
* 上传文件配置
*/
Expand Down Expand Up @@ -88,14 +84,6 @@ public void setSignatureSecret(String signatureSecret) {
this.signatureSecret = signatureSecret;
}

public Shiro getShiro() {
return shiro;
}

public void setShiro(Shiro shiro) {
this.shiro = shiro;
}

public Path getPath() {
return path;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.CommonAPI;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
Expand All @@ -11,6 +10,7 @@
import org.jeecg.common.util.CommonUtils;
import org.jeecg.common.util.SpringContextUtils;
import org.jeecg.config.JeecgBaseConfig;
import org.jeecg.config.security.utils.SecureUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

Expand Down Expand Up @@ -63,7 +63,7 @@ public boolean preHandle(HttpServletRequest request, HttpServletResponse respons
if (jeecgBaseConfig.getFirewall()!=null && LowCodeModeInterceptor.LOW_CODE_MODE_PROD.equals(jeecgBaseConfig.getFirewall().getLowCodeMode())) {
String requestURI = request.getRequestURI().substring(request.getContextPath().length());
log.info("低代码模式,拦截请求路径:" + requestURI);
LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
LoginUser loginUser = SecureUtil.currentUser();
Set<String> hasRoles = null;
if (loginUser == null) {
loginUser = commonAPI.getUserByName(JwtUtil.getUserNameByToken(SpringContextUtils.getHttpServletRequest()));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,11 @@
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.config.TenantContext;
import org.jeecg.common.constant.TenantConstant;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.config.security.utils.SecureUtil;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
Expand Down Expand Up @@ -173,7 +173,7 @@ public void setProperties(Properties properties) {
private LoginUser getLoginUser() {
LoginUser sysUser = null;
try {
sysUser = SecurityUtils.getSubject().getPrincipal() != null ? (LoginUser) SecurityUtils.getSubject().getPrincipal() : null;
sysUser = SecureUtil.currentUser() != null ? SecureUtil.currentUser() : null;
} catch (Exception e) {
//e.printStackTrace();
sysUser = null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,4 +28,9 @@ public class LoginType {
* 扫码登录
*/
public static final String SCAN = "scan";

/**
* 所有联合登录,比如github\钉钉\企业微信\微信
*/
public static final String SOCIAL = "social";
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,14 @@
import com.nimbusds.jose.jwk.source.JWKSource;
import com.nimbusds.jose.proc.SecurityContext;
import lombok.AllArgsConstructor;
import org.jeecg.config.security.app.AppGrantAuthenticationConvert;
import org.jeecg.config.security.app.AppGrantAuthenticationProvider;
import org.jeecg.config.security.password.PasswordGrantAuthenticationConvert;
import org.jeecg.config.security.password.PasswordGrantAuthenticationProvider;
import org.jeecg.config.security.phone.PhoneGrantAuthenticationConvert;
import org.jeecg.config.security.phone.PhoneGrantAuthenticationProvider;
import org.jeecg.config.security.social.SocialGrantAuthenticationConvert;
import org.jeecg.config.security.social.SocialGrantAuthenticationProvider;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
Expand All @@ -17,6 +23,7 @@
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
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.configurers.AbstractHttpConfigurer;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.jwt.JwtDecoder;
Expand Down Expand Up @@ -47,7 +54,7 @@
*/
@Configuration
@EnableWebSecurity
@EnableMethodSecurity(jsr250Enabled = true, securedEnabled = true)
@EnableMethodSecurity
@AllArgsConstructor
public class SecurityConfig {

Expand All @@ -62,6 +69,12 @@ public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity h
http.getConfigurer(OAuth2AuthorizationServerConfigurer.class)
.tokenEndpoint(tokenEndpoint -> tokenEndpoint.accessTokenRequestConverter(new PasswordGrantAuthenticationConvert())
.authenticationProvider(new PasswordGrantAuthenticationProvider(authorizationService, tokenGenerator())))
.tokenEndpoint(tokenEndpoint -> tokenEndpoint.accessTokenRequestConverter(new PhoneGrantAuthenticationConvert())
.authenticationProvider(new PhoneGrantAuthenticationProvider(authorizationService, tokenGenerator())))
.tokenEndpoint(tokenEndpoint -> tokenEndpoint.accessTokenRequestConverter(new AppGrantAuthenticationConvert())
.authenticationProvider(new AppGrantAuthenticationProvider(authorizationService, tokenGenerator())))
.tokenEndpoint(tokenEndpoint -> tokenEndpoint.accessTokenRequestConverter(new SocialGrantAuthenticationConvert())
.authenticationProvider(new SocialGrantAuthenticationProvider(authorizationService, tokenGenerator())))
//开启OpenID Connect 1.0(其中oidc为OpenID Connect的缩写)。 访问 /.well-known/openid-configuration即可获取认证信息
.oidc(Customizer.withDefaults()); // Enable OpenID Connect 1.0
http
Expand Down Expand Up @@ -153,6 +166,7 @@ public SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http)
config.setAllowedMethods(Arrays.asList("HEAD", "GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"));
return config;
}))
.csrf(AbstractHttpConfigurer::disable)
.oauth2ResourceServer(oauth2 -> oauth2.jwt(Customizer.withDefaults()));
return http.build();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,11 +68,11 @@ public AppGrantAuthenticationProvider(OAuth2AuthorizationService authorizationSe

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
PasswordGrantAuthenticationToken passwordGrantAuthenticationToken = (PasswordGrantAuthenticationToken) authentication;
Map<String, Object> additionalParameter = passwordGrantAuthenticationToken.getAdditionalParameters();
AppGrantAuthenticationToken appGrantAuthenticationToken = (AppGrantAuthenticationToken) authentication;
Map<String, Object> additionalParameter = appGrantAuthenticationToken.getAdditionalParameters();

// 授权类型
AuthorizationGrantType authorizationGrantType = passwordGrantAuthenticationToken.getGrantType();
AuthorizationGrantType authorizationGrantType = appGrantAuthenticationToken.getGrantType();
// 用户名
String username = (String) additionalParameter.get(OAuth2ParameterNames.USERNAME);
// 密码
Expand Down Expand Up @@ -105,7 +105,7 @@ public Authentication authenticate(Authentication authentication) throws Authent
throw new JeecgCaptchaException(HttpStatus.PRECONDITION_FAILED.value(), "验证码错误");
}

OAuth2ClientAuthenticationToken clientPrincipal = getAuthenticatedClientElseThrowInvalidClient(passwordGrantAuthenticationToken);
OAuth2ClientAuthenticationToken clientPrincipal = getAuthenticatedClientElseThrowInvalidClient(appGrantAuthenticationToken);
RegisteredClient registeredClient = clientPrincipal.getRegisteredClient();

if (!registeredClient.getAuthorizationGrantTypes().contains(authorizationGrantType)) {
Expand All @@ -132,7 +132,7 @@ public Authentication authenticate(Authentication authentication) throws Authent
.authorizationServerContext(AuthorizationServerContextHolder.getContext())
.authorizationGrantType(authorizationGrantType)
.authorizedScopes(requestScopeSet)
.authorizationGrant(passwordGrantAuthenticationToken);
.authorizationGrant(appGrantAuthenticationToken);

OAuth2Authorization.Builder authorizationBuilder = OAuth2Authorization.withRegisteredClient(registeredClient)
.principalName(clientPrincipal.getName())
Expand Down Expand Up @@ -212,7 +212,7 @@ public Authentication authenticate(Authentication authentication) throws Authent

@Override
public boolean supports(Class<?> authentication) {
return PasswordGrantAuthenticationToken.class.isAssignableFrom(authentication);
return AppGrantAuthenticationToken.class.isAssignableFrom(authentication);
}

private static OAuth2ClientAuthenticationToken getAuthenticatedClientElseThrowInvalidClient(Authentication authentication) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,7 @@ public Authentication convert(HttpServletRequest request) {

// 验证码
String captcha = parameters.getFirst("captcha");
if (!StringUtils.hasText(captcha) ||
parameters.get(OAuth2ParameterNames.USERNAME).size() != 1) {
if (!StringUtils.hasText(captcha)) {
throw new OAuth2AuthenticationException("无效请求,验证码不能为空!");
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,11 +68,11 @@ public PhoneGrantAuthenticationProvider(OAuth2AuthorizationService authorization

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
PasswordGrantAuthenticationToken passwordGrantAuthenticationToken = (PasswordGrantAuthenticationToken) authentication;
Map<String, Object> additionalParameter = passwordGrantAuthenticationToken.getAdditionalParameters();
PhoneGrantAuthenticationToken phoneGrantAuthenticationToken = (PhoneGrantAuthenticationToken) authentication;
Map<String, Object> additionalParameter = phoneGrantAuthenticationToken.getAdditionalParameters();

// 授权类型
AuthorizationGrantType authorizationGrantType = passwordGrantAuthenticationToken.getGrantType();
AuthorizationGrantType authorizationGrantType = phoneGrantAuthenticationToken.getGrantType();
// 手机号
String phone = (String) additionalParameter.get("mobile");

Expand Down Expand Up @@ -102,7 +102,7 @@ public Authentication authenticate(Authentication authentication) throws Authent
throw new JeecgBootException("手机验证码错误");
}

OAuth2ClientAuthenticationToken clientPrincipal = getAuthenticatedClientElseThrowInvalidClient(passwordGrantAuthenticationToken);
OAuth2ClientAuthenticationToken clientPrincipal = getAuthenticatedClientElseThrowInvalidClient(phoneGrantAuthenticationToken);
RegisteredClient registeredClient = clientPrincipal.getRegisteredClient();

if (!registeredClient.getAuthorizationGrantTypes().contains(authorizationGrantType)) {
Expand All @@ -118,7 +118,7 @@ public Authentication authenticate(Authentication authentication) throws Authent
.authorizationServerContext(AuthorizationServerContextHolder.getContext())
.authorizationGrantType(authorizationGrantType)
.authorizedScopes(requestScopeSet)
.authorizationGrant(passwordGrantAuthenticationToken);
.authorizationGrant(phoneGrantAuthenticationToken);

OAuth2Authorization.Builder authorizationBuilder = OAuth2Authorization.withRegisteredClient(registeredClient)
.principalName(clientPrincipal.getName())
Expand Down Expand Up @@ -195,7 +195,7 @@ public Authentication authenticate(Authentication authentication) throws Authent

@Override
public boolean supports(Class<?> authentication) {
return PasswordGrantAuthenticationToken.class.isAssignableFrom(authentication);
return PhoneGrantAuthenticationToken.class.isAssignableFrom(authentication);
}

private static OAuth2ClientAuthenticationToken getAuthenticatedClientElseThrowInvalidClient(Authentication authentication) {
Expand Down
Loading