mirror of
https://gitee.com/y_project/RuoYi-Cloud.git
synced 2026-01-29 04:51:58 +08:00
修改授权相关
This commit is contained in:
@@ -7,7 +7,7 @@
|
||||
<version>2.0.0</version>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
|
||||
<artifactId>ruoyi-common-security</artifactId>
|
||||
|
||||
<description>
|
||||
@@ -15,19 +15,19 @@
|
||||
</description>
|
||||
|
||||
<dependencies>
|
||||
|
||||
|
||||
<!-- Spring Security Oauth2 -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-oauth2</artifactId>
|
||||
</dependency>
|
||||
|
||||
|
||||
<!-- RuoYi Api System -->
|
||||
<dependency>
|
||||
<groupId>com.ruoyi</groupId>
|
||||
<artifactId>ruoyi-api-system</artifactId>
|
||||
</dependency>
|
||||
|
||||
|
||||
</dependencies>
|
||||
|
||||
</project>
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
package com.ruoyi.common.security.config;
|
||||
|
||||
import com.ruoyi.common.security.handler.AuthenticationEntryPointImpl;
|
||||
import com.ruoyi.common.security.handler.CustomAccessDeniedHandler;
|
||||
import com.ruoyi.common.security.handler.CustomResponseErrorHandler;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.autoconfigure.security.oauth2.OAuth2ClientProperties;
|
||||
import org.springframework.boot.autoconfigure.security.oauth2.resource.ResourceServerProperties;
|
||||
@@ -20,7 +23,7 @@ import org.springframework.web.client.RestTemplate;
|
||||
|
||||
/**
|
||||
* oauth2 服务配置
|
||||
*
|
||||
*
|
||||
* @author ruoyi
|
||||
*/
|
||||
@Configuration
|
||||
@@ -33,6 +36,9 @@ public class ResourceServerConfig extends ResourceServerConfigurerAdapter
|
||||
@Autowired
|
||||
private OAuth2ClientProperties oAuth2ClientProperties;
|
||||
|
||||
@Autowired
|
||||
private CustomAccessDeniedHandler customAccessDeniedHandler;
|
||||
|
||||
@Bean
|
||||
public AuthIgnoreConfig authIgnoreConfig()
|
||||
{
|
||||
@@ -44,10 +50,23 @@ public class ResourceServerConfig extends ResourceServerConfigurerAdapter
|
||||
public RestTemplate restTemplate()
|
||||
{
|
||||
RestTemplate restTemplate = new RestTemplate();
|
||||
restTemplate.setErrorHandler(new DefaultResponseErrorHandler());
|
||||
// 设置一个空的 异常处理
|
||||
restTemplate.setErrorHandler(getErrorHandler());
|
||||
return restTemplate;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public CustomResponseErrorHandler getErrorHandler()
|
||||
{
|
||||
return new CustomResponseErrorHandler();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public AuthenticationEntryPointImpl getUnAuthorizedHandler()
|
||||
{
|
||||
return new AuthenticationEntryPointImpl();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public ResourceServerTokenServices tokenServices()
|
||||
{
|
||||
@@ -60,6 +79,7 @@ public class ResourceServerConfig extends ResourceServerConfigurerAdapter
|
||||
remoteTokenServices.setClientSecret(oAuth2ClientProperties.getClientSecret());
|
||||
remoteTokenServices.setRestTemplate(restTemplate());
|
||||
remoteTokenServices.setAccessTokenConverter(accessTokenConverter);
|
||||
|
||||
return remoteTokenServices;
|
||||
}
|
||||
|
||||
@@ -67,8 +87,7 @@ public class ResourceServerConfig extends ResourceServerConfigurerAdapter
|
||||
public void configure(HttpSecurity http) throws Exception
|
||||
{
|
||||
http.csrf().disable();
|
||||
ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry = http
|
||||
.authorizeRequests();
|
||||
ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry = http.authorizeRequests();
|
||||
// 不登录可以访问
|
||||
authIgnoreConfig().getUrls().forEach(url -> registry.antMatchers(url).permitAll());
|
||||
registry.anyRequest().authenticated();
|
||||
@@ -77,6 +96,7 @@ public class ResourceServerConfig extends ResourceServerConfigurerAdapter
|
||||
@Override
|
||||
public void configure(ResourceServerSecurityConfigurer resources)
|
||||
{
|
||||
resources.authenticationEntryPoint(getUnAuthorizedHandler()).accessDeniedHandler(customAccessDeniedHandler);
|
||||
resources.tokenServices(tokenServices());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ import com.ruoyi.common.core.utils.StringUtils;
|
||||
|
||||
/**
|
||||
* 导入 SecurityImportBeanDefinitionRegistrar 自动加载类
|
||||
*
|
||||
*
|
||||
* @author ruoyi
|
||||
*/
|
||||
public class SecurityImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
package com.ruoyi.common.security.granter;
|
||||
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
|
||||
import org.springframework.security.oauth2.provider.*;
|
||||
import org.springframework.security.oauth2.provider.token.AbstractTokenGranter;
|
||||
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
|
||||
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
public abstract class AbstractCustomTokenGranter extends AbstractTokenGranter {
|
||||
|
||||
private final OAuth2RequestFactory requestFactory;
|
||||
|
||||
protected AbstractCustomTokenGranter(AuthorizationServerTokenServices tokenServices, ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory, String grantType) {
|
||||
super(tokenServices, clientDetailsService, requestFactory, grantType);
|
||||
this.requestFactory = requestFactory;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
|
||||
Map<String, String> parameters = tokenRequest.getRequestParameters();
|
||||
UserDetails customUser = getCustomUser(parameters);
|
||||
if (customUser == null) {
|
||||
throw new InvalidGrantException("无法获取用户信息");
|
||||
}
|
||||
OAuth2Request storedOAuth2Request = this.requestFactory.createOAuth2Request(client, tokenRequest);
|
||||
PreAuthenticatedAuthenticationToken authentication = new PreAuthenticatedAuthenticationToken(customUser, null, customUser.getAuthorities());
|
||||
authentication.setDetails(customUser);
|
||||
OAuth2Authentication oAuth2Authentication = new OAuth2Authentication(storedOAuth2Request, authentication);
|
||||
return oAuth2Authentication;
|
||||
}
|
||||
|
||||
protected abstract UserDetails getCustomUser(Map<String, String> parameters);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.ruoyi.common.security.granter;
|
||||
|
||||
import com.ruoyi.common.security.service.CustomUserDetailsService;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.security.oauth2.provider.ClientDetailsService;
|
||||
import org.springframework.security.oauth2.provider.OAuth2RequestFactory;
|
||||
|
||||
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
public class PasswordCustomTokenGranter extends AbstractCustomTokenGranter {
|
||||
|
||||
protected CustomUserDetailsService userDetailsService;
|
||||
|
||||
public PasswordCustomTokenGranter(CustomUserDetailsService userDetailsService, AuthorizationServerTokenServices tokenServices, ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory) {
|
||||
super(tokenServices, clientDetailsService, requestFactory, "password");
|
||||
this.userDetailsService = userDetailsService;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected UserDetails getCustomUser(Map<String, String> parameters) {
|
||||
String username = parameters.get("username");
|
||||
String password = parameters.get("password");
|
||||
return userDetailsService.loadUserByUsernameAndPassword(username, password);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.ruoyi.common.security.handler;
|
||||
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.ruoyi.common.core.constant.HttpStatus;
|
||||
import com.ruoyi.common.core.utils.ServletUtils;
|
||||
import com.ruoyi.common.core.utils.StringUtils;
|
||||
import com.ruoyi.common.core.web.domain.AjaxResult;
|
||||
import org.springframework.security.core.AuthenticationException;
|
||||
import org.springframework.security.web.AuthenticationEntryPoint;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
import java.io.Serializable;
|
||||
|
||||
/**
|
||||
* 认证失败处理类 返回未授权
|
||||
*
|
||||
* @author cleanwarm
|
||||
*/
|
||||
@Component
|
||||
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint, Serializable
|
||||
{
|
||||
private static final long serialVersionUID = -8970718410437077606L;
|
||||
|
||||
@Override
|
||||
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e)
|
||||
throws IOException
|
||||
{
|
||||
int code = HttpStatus.UNAUTHORIZED;
|
||||
String msg = StringUtils.format("请求访问:{},认证失败,无法访问系统资源", request.getRequestURI());
|
||||
ServletUtils.renderString(response, JSON.toJSONString(AjaxResult.error(code, msg)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.ruoyi.common.security.handler;
|
||||
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.http.client.ClientHttpResponse;
|
||||
import org.springframework.web.client.ResponseErrorHandler;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
|
||||
public class CustomResponseErrorHandler implements ResponseErrorHandler {
|
||||
|
||||
|
||||
@Override
|
||||
public boolean hasError(ClientHttpResponse response) throws IOException {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handleError(ClientHttpResponse response) throws IOException {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handleError(URI url, HttpMethod method, ClientHttpResponse response) throws IOException {
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package com.ruoyi.common.security.service;
|
||||
|
||||
import com.ruoyi.common.core.domain.R;
|
||||
import com.ruoyi.common.core.enums.UserStatus;
|
||||
import com.ruoyi.common.core.exception.BaseException;
|
||||
import com.ruoyi.common.core.utils.StringUtils;
|
||||
import com.ruoyi.common.security.domain.LoginUser;
|
||||
import com.ruoyi.system.api.RemoteUserService;
|
||||
import com.ruoyi.system.api.domain.SysUser;
|
||||
import com.ruoyi.system.api.model.UserInfo;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.core.authority.AuthorityUtils;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
||||
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
@Service
|
||||
public class CustomUserDetailsService {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(CustomUserDetailsService.class);
|
||||
|
||||
@Autowired
|
||||
private RemoteUserService remoteUserService;
|
||||
|
||||
public UserDetails loadUserByUsernameAndPassword(String username, String password) {
|
||||
// 判断成功后返回用户细节
|
||||
R<UserInfo> userResult = remoteUserService.login(username,password);
|
||||
checkUser(userResult, username,password);
|
||||
return getUserDetails(userResult);
|
||||
}
|
||||
public void checkUser(R<UserInfo> userResult, String username, String password)
|
||||
{
|
||||
if (StringUtils.isNull(userResult) || StringUtils.isNull(userResult.getData()))
|
||||
{
|
||||
log.info("登录用户:{} 不存在.", username);
|
||||
// throw new UsernameNotFoundException("登录用户:" + username + " 不存在");
|
||||
throw new OAuth2Exception("账号或密码不正确");//
|
||||
}
|
||||
else if (UserStatus.DELETED.getCode().equals(userResult.getData().getSysUser().getDelFlag()))
|
||||
{
|
||||
log.info("登录用户:{} 已被删除.", username);
|
||||
throw new OAuth2Exception("对不起,您的账号:" + username + " 已被删除");
|
||||
}
|
||||
else if (UserStatus.DISABLE.getCode().equals(userResult.getData().getSysUser().getStatus()))
|
||||
{
|
||||
log.info("登录用户:{} 已被停用.", username);
|
||||
throw new OAuth2Exception("对不起,您的账号:" + username + " 已停用");
|
||||
}
|
||||
}
|
||||
private UserDetails getUserDetails(R<UserInfo> result)
|
||||
{
|
||||
UserInfo info = result.getData();
|
||||
Set<String> dbAuthsSet = new HashSet<String>();
|
||||
if (StringUtils.isNotEmpty(info.getRoles()))
|
||||
{
|
||||
// 获取角色
|
||||
dbAuthsSet.addAll(info.getRoles());
|
||||
// 获取权限
|
||||
dbAuthsSet.addAll(info.getPermissions());
|
||||
}
|
||||
|
||||
Collection<? extends GrantedAuthority> authorities = AuthorityUtils
|
||||
.createAuthorityList(dbAuthsSet.toArray(new String[0]));
|
||||
SysUser user = info.getSysUser();
|
||||
|
||||
return new LoginUser(user.getUserId(), user.getUserName(), user.getPassword(), true, true, true, true,
|
||||
authorities);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,5 +1,4 @@
|
||||
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
|
||||
com.ruoyi.common.security.service.UserDetailsServiceImpl,\
|
||||
com.ruoyi.common.security.service.CustomUserDetailsService,\
|
||||
com.ruoyi.common.security.handler.CustomAccessDeniedHandler
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user