修改授权相关
This commit is contained in:
parent
de0c51f5a7
commit
d6844f19bd
|
|
@ -7,10 +7,11 @@ import com.ruoyi.common.core.constant.ServiceNameConstants;
|
|||
import com.ruoyi.common.core.domain.R;
|
||||
import com.ruoyi.system.api.factory.RemoteUserFallbackFactory;
|
||||
import com.ruoyi.system.api.model.UserInfo;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
|
||||
/**
|
||||
* 用户服务
|
||||
*
|
||||
*
|
||||
* @author ruoyi
|
||||
*/
|
||||
@FeignClient(contextId = "remoteUserService", value = ServiceNameConstants.SYSTEM_SERVICE, fallbackFactory = RemoteUserFallbackFactory.class)
|
||||
|
|
@ -24,4 +25,7 @@ public interface RemoteUserService
|
|||
*/
|
||||
@GetMapping(value = "/user/info/{username}")
|
||||
public R<UserInfo> getUserInfo(@PathVariable("username") String username);
|
||||
|
||||
@GetMapping(value = "/user/login")
|
||||
public R<UserInfo> login(@RequestParam("username")String username, @RequestParam("password")String password);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@ import feign.hystrix.FallbackFactory;
|
|||
|
||||
/**
|
||||
* 用户服务降级处理
|
||||
*
|
||||
*
|
||||
* @author ruoyi
|
||||
*/
|
||||
@Component
|
||||
|
|
@ -29,6 +29,12 @@ public class RemoteUserFallbackFactory implements FallbackFactory<RemoteUserServ
|
|||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public R<UserInfo> login(String username,String password)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -56,8 +56,19 @@
|
|||
<dependency>
|
||||
<groupId>com.ruoyi</groupId>
|
||||
<artifactId>ruoyi-common-redis</artifactId>
|
||||
</dependency><dependency><groupId>com.ruoyi</groupId><artifactId>ruoyi-common-swagger</artifactId>
|
||||
</dependency>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.ruoyi</groupId>
|
||||
<artifactId>ruoyi-common-swagger</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- Swagger -->
|
||||
<dependency>
|
||||
<groupId>io.springfox</groupId>
|
||||
<artifactId>springfox-swagger-ui</artifactId>
|
||||
<version>${swagger.fox.version}</version>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
|
|
|
|||
|
|
@ -1,8 +1,10 @@
|
|||
package com.ruoyi.auth.config;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.*;
|
||||
import javax.sql.DataSource;
|
||||
|
||||
import com.ruoyi.common.security.granter.PasswordCustomTokenGranter;
|
||||
import com.ruoyi.common.security.service.CustomUserDetailsService;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
|
@ -17,7 +19,8 @@ import org.springframework.security.oauth2.config.annotation.web.configuration.A
|
|||
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
|
||||
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
|
||||
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
|
||||
import org.springframework.security.oauth2.provider.OAuth2Authentication;
|
||||
import org.springframework.security.oauth2.provider.*;
|
||||
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
|
||||
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
|
||||
import org.springframework.security.oauth2.provider.token.TokenStore;
|
||||
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;
|
||||
|
|
@ -29,7 +32,7 @@ import com.ruoyi.common.security.service.RedisClientDetailsService;
|
|||
|
||||
/**
|
||||
* OAuth2 认证服务配置
|
||||
*
|
||||
*
|
||||
* @author ruoyi
|
||||
*/
|
||||
@Configuration
|
||||
|
|
@ -45,8 +48,11 @@ public class AuthServerConfig extends AuthorizationServerConfigurerAdapter
|
|||
@Autowired
|
||||
private RedisConnectionFactory redisConnectionFactory;
|
||||
|
||||
// @Autowired
|
||||
// private UserDetailsService userDetailsService;
|
||||
|
||||
@Autowired
|
||||
private UserDetailsService userDetailsService;
|
||||
private CustomUserDetailsService customUserDetailsService;
|
||||
|
||||
@Autowired
|
||||
private TokenEnhancer tokenEnhancer;
|
||||
|
|
@ -58,6 +64,7 @@ public class AuthServerConfig extends AuthorizationServerConfigurerAdapter
|
|||
public void configure(AuthorizationServerEndpointsConfigurer endpoints)
|
||||
{
|
||||
endpoints
|
||||
.tokenGranter(new CompositeTokenGranter(getTokenGranters(endpoints.getTokenServices(), endpoints.getClientDetailsService(), endpoints.getOAuth2RequestFactory())))
|
||||
// 请求方式
|
||||
.allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST)
|
||||
// 指定token存储位置
|
||||
|
|
@ -65,15 +72,20 @@ public class AuthServerConfig extends AuthorizationServerConfigurerAdapter
|
|||
// 自定义生成令牌
|
||||
.tokenEnhancer(tokenEnhancer)
|
||||
// 用户账号密码认证
|
||||
.userDetailsService(userDetailsService)
|
||||
// .userDetailsService(userDetailsService)
|
||||
// 指定认证管理器
|
||||
.authenticationManager(authenticationManager)
|
||||
// 是否重复使用 refresh_token
|
||||
.reuseRefreshTokens(false)
|
||||
.reuseRefreshTokens(false);
|
||||
// 自定义异常处理
|
||||
.exceptionTranslator(new CustomWebResponseExceptionTranslator());
|
||||
// .exceptionTranslator(new CustomWebResponseExceptionTranslator());
|
||||
}
|
||||
|
||||
private List<TokenGranter> getTokenGranters(AuthorizationServerTokenServices tokenServices, ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory) {
|
||||
return new ArrayList<>(Arrays.asList(
|
||||
new PasswordCustomTokenGranter(customUserDetailsService,tokenServices, clientDetailsService, requestFactory)
|
||||
));
|
||||
}
|
||||
/**
|
||||
* 配置令牌端点(Token Endpoint)的安全约束
|
||||
*/
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ 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.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
|
||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
|
|
@ -41,16 +42,17 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter
|
|||
// auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
|
||||
// }
|
||||
|
||||
// @Override
|
||||
// protected void configure(HttpSecurity http) throws Exception
|
||||
// {
|
||||
// http
|
||||
// .authorizeRequests()
|
||||
// .antMatchers(
|
||||
// "/actuator/**",
|
||||
// "/oauth/*",
|
||||
// "/token/**").permitAll()
|
||||
// .anyRequest().authenticated()
|
||||
// .and().csrf().disable();
|
||||
// }
|
||||
@Override
|
||||
protected void configure(HttpSecurity http) throws Exception
|
||||
{
|
||||
http
|
||||
.authorizeRequests()
|
||||
.antMatchers(
|
||||
"/actuator/**",
|
||||
"/v2/**",
|
||||
"/oauth/*",
|
||||
"/token/**").permitAll()
|
||||
.anyRequest().authenticated()
|
||||
.and().csrf().disable();
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ import com.ruoyi.common.core.domain.R;
|
|||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
|
||||
import org.springframework.security.oauth2.common.OAuth2AccessToken;
|
||||
import org.springframework.security.oauth2.provider.endpoint.CheckTokenEndpoint;
|
||||
import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint;
|
||||
import org.springframework.web.HttpRequestMethodNotSupportedException;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
|
@ -22,6 +23,8 @@ public class OauthController {
|
|||
@Autowired
|
||||
private TokenEndpoint tokenEndpoint;
|
||||
|
||||
// @Autowired
|
||||
// private CheckTokenEndpoint checkTokenEndpoint;
|
||||
/**
|
||||
*
|
||||
* @param principal
|
||||
|
|
@ -39,6 +42,12 @@ public class OauthController {
|
|||
return custom(tokenEndpoint.postAccessToken(principal, parameters).getBody());
|
||||
}
|
||||
|
||||
// @RequestMapping(value = "/check_token")
|
||||
// @ResponseBody
|
||||
// public R<?> checkToken(@RequestParam("token") String value) throws HttpRequestMethodNotSupportedException {
|
||||
// return R.ok(checkTokenEndpoint.checkToken(value));
|
||||
// }
|
||||
|
||||
//自定义返回格式
|
||||
private R<?> custom(OAuth2AccessToken accessToken) {
|
||||
DefaultOAuth2AccessToken token = (DefaultOAuth2AccessToken) accessToken;
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -28,7 +28,7 @@ public class SwaggerProvider implements SwaggerResourcesProvider
|
|||
|
||||
/**
|
||||
* 聚合其他服务接口
|
||||
*
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
@Override
|
||||
|
|
@ -43,7 +43,7 @@ public class SwaggerProvider implements SwaggerResourcesProvider
|
|||
.contains(routeDefinition.getId()))
|
||||
.forEach(routeDefinition -> routeDefinition.getPredicates().stream()
|
||||
.filter(predicateDefinition -> "Path".equalsIgnoreCase(predicateDefinition.getName()))
|
||||
.filter(predicateDefinition -> !"ruoyi-auth".equalsIgnoreCase(routeDefinition.getId()))
|
||||
// .filter(predicateDefinition -> !"ruoyi-auth".equalsIgnoreCase(routeDefinition.getId()))
|
||||
.forEach(predicateDefinition -> resourceList
|
||||
.add(swaggerResource(routeDefinition.getId(), predicateDefinition.getArgs()
|
||||
.get(NameUtils.GENERATED_NAME_PREFIX + "0").replace("/**", SWAGGER2URL)))));
|
||||
|
|
|
|||
|
|
@ -15,13 +15,13 @@ import reactor.core.publisher.Mono;
|
|||
|
||||
/**
|
||||
* 验证码过滤器
|
||||
*
|
||||
*
|
||||
* @author ruoyi
|
||||
*/
|
||||
@Component
|
||||
public class ValidateCodeFilter extends AbstractGatewayFilterFactory<Object>
|
||||
{
|
||||
private final static String AUTH_URL = "/oauth/token";
|
||||
private final static String AUTH_URL = "/oauth/token1";//"/oauth/token";
|
||||
|
||||
@Autowired
|
||||
private ValidateCodeService validateCodeService;
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ server:
|
|||
port: 8080
|
||||
|
||||
# Spring
|
||||
spring:
|
||||
spring:
|
||||
application:
|
||||
# 应用名称
|
||||
name: ruoyi-gateway
|
||||
|
|
@ -29,7 +29,7 @@ spring:
|
|||
eager: true
|
||||
transport:
|
||||
# 控制台地址
|
||||
dashboard: 127.0.0.1:8718
|
||||
dashboard: 127.0.0.1:8076
|
||||
# nacos配置持久化
|
||||
datasource:
|
||||
ds1:
|
||||
|
|
|
|||
|
|
@ -1,20 +1,25 @@
|
|||
package com.ruoyi.system;
|
||||
|
||||
import com.ruoyi.common.core.domain.R;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.cloud.client.SpringCloudApplication;
|
||||
import com.ruoyi.common.security.annotation.EnableCustomConfig;
|
||||
import com.ruoyi.common.security.annotation.EnableRyFeignClients;
|
||||
import com.ruoyi.common.swagger.annotation.EnableCustomSwagger2;
|
||||
import org.springframework.web.bind.annotation.ControllerAdvice;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.ResponseBody;
|
||||
|
||||
/**
|
||||
* 系统模块
|
||||
*
|
||||
*
|
||||
* @author ruoyi
|
||||
*/
|
||||
@EnableCustomConfig
|
||||
@EnableCustomSwagger2
|
||||
@EnableRyFeignClients
|
||||
@SpringCloudApplication
|
||||
@ControllerAdvice
|
||||
public class RuoYiSystemApplication
|
||||
{
|
||||
public static void main(String[] args)
|
||||
|
|
@ -31,4 +36,11 @@ public class RuoYiSystemApplication
|
|||
" | | \\ / \\ / \n" +
|
||||
" ''-' `'-' `-..-' ");
|
||||
}
|
||||
|
||||
@ResponseBody
|
||||
@ExceptionHandler(Exception.class)
|
||||
public R<?> exceptionHandler(Exception e) {
|
||||
e.printStackTrace();
|
||||
return R.failed(e,e.getMessage());
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -7,14 +7,7 @@ import javax.servlet.http.HttpServletResponse;
|
|||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
import com.ruoyi.common.core.constant.UserConstants;
|
||||
import com.ruoyi.common.core.domain.R;
|
||||
|
|
@ -35,7 +28,7 @@ import com.ruoyi.system.service.ISysUserService;
|
|||
|
||||
/**
|
||||
* 用户信息
|
||||
*
|
||||
*
|
||||
* @author ruoyi
|
||||
*/
|
||||
@RestController
|
||||
|
|
@ -117,9 +110,28 @@ public class SysUserController extends BaseController
|
|||
return R.ok(sysUserVo);
|
||||
}
|
||||
|
||||
@GetMapping("/login")
|
||||
public R<UserInfo> login(@RequestParam("username")String username, @RequestParam("password")String password)
|
||||
{
|
||||
SysUser sysUser = userService.selectUserByUserName(username);
|
||||
if(SecurityUtils.matchesPassword(password,sysUser.getPassword()))
|
||||
{
|
||||
// 角色集合
|
||||
Set<String> roles = permissionService.getRolePermission(sysUser.getUserId());
|
||||
// 权限集合
|
||||
Set<String> permissions = permissionService.getMenuPermission(sysUser.getUserId());
|
||||
UserInfo sysUserVo = new UserInfo();
|
||||
sysUserVo.setSysUser(sysUser);
|
||||
sysUserVo.setRoles(roles);
|
||||
sysUserVo.setPermissions(permissions);
|
||||
return R.ok(sysUserVo);
|
||||
}
|
||||
|
||||
return R.ok(null);
|
||||
}
|
||||
/**
|
||||
* 获取用户信息
|
||||
*
|
||||
*
|
||||
* @return 用户信息
|
||||
*/
|
||||
@GetMapping("getInfo")
|
||||
|
|
|
|||
|
|
@ -1,9 +1,9 @@
|
|||
# Tomcat
|
||||
server:
|
||||
port: 9201
|
||||
port: 9001
|
||||
|
||||
# Spring
|
||||
spring:
|
||||
spring:
|
||||
application:
|
||||
# 应用名称
|
||||
name: ruoyi-system
|
||||
|
|
|
|||
|
|
@ -1,96 +1,96 @@
|
|||
import { login, logout, getInfo } from '@/api/login'
|
||||
import { getToken, setToken, removeToken } from '@/utils/auth'
|
||||
|
||||
const user = {
|
||||
state: {
|
||||
token: getToken(),
|
||||
name: '',
|
||||
avatar: '',
|
||||
roles: [],
|
||||
permissions: []
|
||||
},
|
||||
|
||||
mutations: {
|
||||
SET_TOKEN: (state, token) => {
|
||||
state.token = token
|
||||
},
|
||||
SET_NAME: (state, name) => {
|
||||
state.name = name
|
||||
},
|
||||
SET_AVATAR: (state, avatar) => {
|
||||
state.avatar = avatar
|
||||
},
|
||||
SET_ROLES: (state, roles) => {
|
||||
state.roles = roles
|
||||
},
|
||||
SET_PERMISSIONS: (state, permissions) => {
|
||||
state.permissions = permissions
|
||||
}
|
||||
},
|
||||
|
||||
actions: {
|
||||
// 登录
|
||||
Login({ commit }, userInfo) {
|
||||
const username = userInfo.username.trim()
|
||||
const password = userInfo.password
|
||||
const code = userInfo.code
|
||||
const uuid = userInfo.uuid
|
||||
return new Promise((resolve, reject) => {
|
||||
login(username, password, code, uuid).then(res => {
|
||||
setToken(res.access_token)
|
||||
commit('SET_TOKEN', res.access_token)
|
||||
resolve()
|
||||
}).catch(error => {
|
||||
reject(error)
|
||||
})
|
||||
})
|
||||
},
|
||||
|
||||
// 获取用户信息
|
||||
GetInfo({ commit, state }) {
|
||||
return new Promise((resolve, reject) => {
|
||||
getInfo(state.token).then(res => {
|
||||
const user = res.user
|
||||
const avatar = user.avatar == "" ? require("@/assets/image/profile.jpg") : process.env.VUE_APP_BASE_API + user.avatar;
|
||||
if (res.roles && res.roles.length > 0) { // 验证返回的roles是否是一个非空数组
|
||||
commit('SET_ROLES', res.roles)
|
||||
commit('SET_PERMISSIONS', res.permissions)
|
||||
} else {
|
||||
commit('SET_ROLES', ['ROLE_DEFAULT'])
|
||||
}
|
||||
commit('SET_NAME', user.userName)
|
||||
commit('SET_AVATAR', avatar)
|
||||
resolve(res)
|
||||
}).catch(error => {
|
||||
reject(error)
|
||||
})
|
||||
})
|
||||
},
|
||||
|
||||
// 退出系统
|
||||
LogOut({ commit, state }) {
|
||||
return new Promise((resolve, reject) => {
|
||||
logout(state.token).then(() => {
|
||||
commit('SET_TOKEN', '')
|
||||
commit('SET_ROLES', [])
|
||||
commit('SET_PERMISSIONS', [])
|
||||
removeToken()
|
||||
resolve()
|
||||
}).catch(error => {
|
||||
reject(error)
|
||||
})
|
||||
})
|
||||
},
|
||||
|
||||
// 前端 登出
|
||||
FedLogOut({ commit }) {
|
||||
return new Promise(resolve => {
|
||||
commit('SET_TOKEN', '')
|
||||
removeToken()
|
||||
resolve()
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default user
|
||||
import { login, logout, getInfo } from '@/api/login'
|
||||
import { getToken, setToken, removeToken } from '@/utils/auth'
|
||||
|
||||
const user = {
|
||||
state: {
|
||||
token: getToken(),
|
||||
name: '',
|
||||
avatar: '',
|
||||
roles: [],
|
||||
permissions: []
|
||||
},
|
||||
|
||||
mutations: {
|
||||
SET_TOKEN: (state, token) => {
|
||||
state.token = token
|
||||
},
|
||||
SET_NAME: (state, name) => {
|
||||
state.name = name
|
||||
},
|
||||
SET_AVATAR: (state, avatar) => {
|
||||
state.avatar = avatar
|
||||
},
|
||||
SET_ROLES: (state, roles) => {
|
||||
state.roles = roles
|
||||
},
|
||||
SET_PERMISSIONS: (state, permissions) => {
|
||||
state.permissions = permissions
|
||||
}
|
||||
},
|
||||
|
||||
actions: {
|
||||
// 登录
|
||||
Login({ commit }, userInfo) {
|
||||
const username = userInfo.username.trim()
|
||||
const password = userInfo.password
|
||||
const code = userInfo.code
|
||||
const uuid = userInfo.uuid
|
||||
return new Promise((resolve, reject) => {
|
||||
login(username, password, code, uuid).then(res => {
|
||||
setToken(res.data.access_token)
|
||||
commit('SET_TOKEN', res.data.access_token)
|
||||
resolve()
|
||||
}).catch(error => {
|
||||
reject(error)
|
||||
})
|
||||
})
|
||||
},
|
||||
|
||||
// 获取用户信息
|
||||
GetInfo({ commit, state }) {
|
||||
return new Promise((resolve, reject) => {
|
||||
getInfo(state.token).then(res => {
|
||||
const user = res.user
|
||||
const avatar = user.avatar == "" ? require("@/assets/image/profile.jpg") : process.env.VUE_APP_BASE_API + user.avatar;
|
||||
if (res.roles && res.roles.length > 0) { // 验证返回的roles是否是一个非空数组
|
||||
commit('SET_ROLES', res.roles)
|
||||
commit('SET_PERMISSIONS', res.permissions)
|
||||
} else {
|
||||
commit('SET_ROLES', ['ROLE_DEFAULT'])
|
||||
}
|
||||
commit('SET_NAME', user.userName)
|
||||
commit('SET_AVATAR', avatar)
|
||||
resolve(res)
|
||||
}).catch(error => {
|
||||
reject(error)
|
||||
})
|
||||
})
|
||||
},
|
||||
|
||||
// 退出系统
|
||||
LogOut({ commit, state }) {
|
||||
return new Promise((resolve, reject) => {
|
||||
logout(state.token).then(() => {
|
||||
commit('SET_TOKEN', '')
|
||||
commit('SET_ROLES', [])
|
||||
commit('SET_PERMISSIONS', [])
|
||||
removeToken()
|
||||
resolve()
|
||||
}).catch(error => {
|
||||
reject(error)
|
||||
})
|
||||
})
|
||||
},
|
||||
|
||||
// 前端 登出
|
||||
FedLogOut({ commit }) {
|
||||
return new Promise(resolve => {
|
||||
commit('SET_TOKEN', '')
|
||||
removeToken()
|
||||
resolve()
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default user
|
||||
|
|
|
|||
Loading…
Reference in New Issue