修改授权相关
This commit is contained in:
parent
de0c51f5a7
commit
d6844f19bd
|
|
@ -7,6 +7,7 @@ import com.ruoyi.common.core.constant.ServiceNameConstants;
|
||||||
import com.ruoyi.common.core.domain.R;
|
import com.ruoyi.common.core.domain.R;
|
||||||
import com.ruoyi.system.api.factory.RemoteUserFallbackFactory;
|
import com.ruoyi.system.api.factory.RemoteUserFallbackFactory;
|
||||||
import com.ruoyi.system.api.model.UserInfo;
|
import com.ruoyi.system.api.model.UserInfo;
|
||||||
|
import org.springframework.web.bind.annotation.RequestParam;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 用户服务
|
* 用户服务
|
||||||
|
|
@ -24,4 +25,7 @@ public interface RemoteUserService
|
||||||
*/
|
*/
|
||||||
@GetMapping(value = "/user/info/{username}")
|
@GetMapping(value = "/user/info/{username}")
|
||||||
public R<UserInfo> getUserInfo(@PathVariable("username") String 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);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -29,6 +29,12 @@ public class RemoteUserFallbackFactory implements FallbackFactory<RemoteUserServ
|
||||||
{
|
{
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public R<UserInfo> login(String username,String password)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -56,7 +56,18 @@
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.ruoyi</groupId>
|
<groupId>com.ruoyi</groupId>
|
||||||
<artifactId>ruoyi-common-redis</artifactId>
|
<artifactId>ruoyi-common-redis</artifactId>
|
||||||
</dependency><dependency><groupId>com.ruoyi</groupId><artifactId>ruoyi-common-swagger</artifactId>
|
</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>
|
</dependency>
|
||||||
|
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
|
||||||
|
|
@ -1,8 +1,10 @@
|
||||||
package com.ruoyi.auth.config;
|
package com.ruoyi.auth.config;
|
||||||
|
|
||||||
import java.util.LinkedHashMap;
|
import java.util.*;
|
||||||
import java.util.Map;
|
|
||||||
import javax.sql.DataSource;
|
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.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.context.annotation.Bean;
|
import org.springframework.context.annotation.Bean;
|
||||||
import org.springframework.context.annotation.Configuration;
|
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.configuration.EnableAuthorizationServer;
|
||||||
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
|
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.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.TokenEnhancer;
|
||||||
import org.springframework.security.oauth2.provider.token.TokenStore;
|
import org.springframework.security.oauth2.provider.token.TokenStore;
|
||||||
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;
|
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;
|
||||||
|
|
@ -45,8 +48,11 @@ public class AuthServerConfig extends AuthorizationServerConfigurerAdapter
|
||||||
@Autowired
|
@Autowired
|
||||||
private RedisConnectionFactory redisConnectionFactory;
|
private RedisConnectionFactory redisConnectionFactory;
|
||||||
|
|
||||||
|
// @Autowired
|
||||||
|
// private UserDetailsService userDetailsService;
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
private UserDetailsService userDetailsService;
|
private CustomUserDetailsService customUserDetailsService;
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
private TokenEnhancer tokenEnhancer;
|
private TokenEnhancer tokenEnhancer;
|
||||||
|
|
@ -58,6 +64,7 @@ public class AuthServerConfig extends AuthorizationServerConfigurerAdapter
|
||||||
public void configure(AuthorizationServerEndpointsConfigurer endpoints)
|
public void configure(AuthorizationServerEndpointsConfigurer endpoints)
|
||||||
{
|
{
|
||||||
endpoints
|
endpoints
|
||||||
|
.tokenGranter(new CompositeTokenGranter(getTokenGranters(endpoints.getTokenServices(), endpoints.getClientDetailsService(), endpoints.getOAuth2RequestFactory())))
|
||||||
// 请求方式
|
// 请求方式
|
||||||
.allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST)
|
.allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST)
|
||||||
// 指定token存储位置
|
// 指定token存储位置
|
||||||
|
|
@ -65,15 +72,20 @@ public class AuthServerConfig extends AuthorizationServerConfigurerAdapter
|
||||||
// 自定义生成令牌
|
// 自定义生成令牌
|
||||||
.tokenEnhancer(tokenEnhancer)
|
.tokenEnhancer(tokenEnhancer)
|
||||||
// 用户账号密码认证
|
// 用户账号密码认证
|
||||||
.userDetailsService(userDetailsService)
|
// .userDetailsService(userDetailsService)
|
||||||
// 指定认证管理器
|
// 指定认证管理器
|
||||||
.authenticationManager(authenticationManager)
|
.authenticationManager(authenticationManager)
|
||||||
// 是否重复使用 refresh_token
|
// 是否重复使用 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)的安全约束
|
* 配置令牌端点(Token Endpoint)的安全约束
|
||||||
*/
|
*/
|
||||||
|
|
|
||||||
|
|
@ -4,6 +4,7 @@ import org.springframework.context.annotation.Bean;
|
||||||
import org.springframework.context.annotation.Configuration;
|
import org.springframework.context.annotation.Configuration;
|
||||||
import org.springframework.core.annotation.Order;
|
import org.springframework.core.annotation.Order;
|
||||||
import org.springframework.security.authentication.AuthenticationManager;
|
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.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
|
||||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||||
|
|
@ -41,16 +42,17 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter
|
||||||
// auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
|
// auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
|
||||||
// }
|
// }
|
||||||
|
|
||||||
// @Override
|
@Override
|
||||||
// protected void configure(HttpSecurity http) throws Exception
|
protected void configure(HttpSecurity http) throws Exception
|
||||||
// {
|
{
|
||||||
// http
|
http
|
||||||
// .authorizeRequests()
|
.authorizeRequests()
|
||||||
// .antMatchers(
|
.antMatchers(
|
||||||
// "/actuator/**",
|
"/actuator/**",
|
||||||
// "/oauth/*",
|
"/v2/**",
|
||||||
// "/token/**").permitAll()
|
"/oauth/*",
|
||||||
// .anyRequest().authenticated()
|
"/token/**").permitAll()
|
||||||
// .and().csrf().disable();
|
.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.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
|
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
|
||||||
import org.springframework.security.oauth2.common.OAuth2AccessToken;
|
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.security.oauth2.provider.endpoint.TokenEndpoint;
|
||||||
import org.springframework.web.HttpRequestMethodNotSupportedException;
|
import org.springframework.web.HttpRequestMethodNotSupportedException;
|
||||||
import org.springframework.web.bind.annotation.*;
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
@ -22,6 +23,8 @@ public class OauthController {
|
||||||
@Autowired
|
@Autowired
|
||||||
private TokenEndpoint tokenEndpoint;
|
private TokenEndpoint tokenEndpoint;
|
||||||
|
|
||||||
|
// @Autowired
|
||||||
|
// private CheckTokenEndpoint checkTokenEndpoint;
|
||||||
/**
|
/**
|
||||||
*
|
*
|
||||||
* @param principal
|
* @param principal
|
||||||
|
|
@ -39,6 +42,12 @@ public class OauthController {
|
||||||
return custom(tokenEndpoint.postAccessToken(principal, parameters).getBody());
|
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) {
|
private R<?> custom(OAuth2AccessToken accessToken) {
|
||||||
DefaultOAuth2AccessToken token = (DefaultOAuth2AccessToken) accessToken;
|
DefaultOAuth2AccessToken token = (DefaultOAuth2AccessToken) accessToken;
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,8 @@
|
||||||
package com.ruoyi.common.security.config;
|
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.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.boot.autoconfigure.security.oauth2.OAuth2ClientProperties;
|
import org.springframework.boot.autoconfigure.security.oauth2.OAuth2ClientProperties;
|
||||||
import org.springframework.boot.autoconfigure.security.oauth2.resource.ResourceServerProperties;
|
import org.springframework.boot.autoconfigure.security.oauth2.resource.ResourceServerProperties;
|
||||||
|
|
@ -33,6 +36,9 @@ public class ResourceServerConfig extends ResourceServerConfigurerAdapter
|
||||||
@Autowired
|
@Autowired
|
||||||
private OAuth2ClientProperties oAuth2ClientProperties;
|
private OAuth2ClientProperties oAuth2ClientProperties;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private CustomAccessDeniedHandler customAccessDeniedHandler;
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
public AuthIgnoreConfig authIgnoreConfig()
|
public AuthIgnoreConfig authIgnoreConfig()
|
||||||
{
|
{
|
||||||
|
|
@ -44,10 +50,23 @@ public class ResourceServerConfig extends ResourceServerConfigurerAdapter
|
||||||
public RestTemplate restTemplate()
|
public RestTemplate restTemplate()
|
||||||
{
|
{
|
||||||
RestTemplate restTemplate = new RestTemplate();
|
RestTemplate restTemplate = new RestTemplate();
|
||||||
restTemplate.setErrorHandler(new DefaultResponseErrorHandler());
|
// 设置一个空的 异常处理
|
||||||
|
restTemplate.setErrorHandler(getErrorHandler());
|
||||||
return restTemplate;
|
return restTemplate;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public CustomResponseErrorHandler getErrorHandler()
|
||||||
|
{
|
||||||
|
return new CustomResponseErrorHandler();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public AuthenticationEntryPointImpl getUnAuthorizedHandler()
|
||||||
|
{
|
||||||
|
return new AuthenticationEntryPointImpl();
|
||||||
|
}
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
public ResourceServerTokenServices tokenServices()
|
public ResourceServerTokenServices tokenServices()
|
||||||
{
|
{
|
||||||
|
|
@ -60,6 +79,7 @@ public class ResourceServerConfig extends ResourceServerConfigurerAdapter
|
||||||
remoteTokenServices.setClientSecret(oAuth2ClientProperties.getClientSecret());
|
remoteTokenServices.setClientSecret(oAuth2ClientProperties.getClientSecret());
|
||||||
remoteTokenServices.setRestTemplate(restTemplate());
|
remoteTokenServices.setRestTemplate(restTemplate());
|
||||||
remoteTokenServices.setAccessTokenConverter(accessTokenConverter);
|
remoteTokenServices.setAccessTokenConverter(accessTokenConverter);
|
||||||
|
|
||||||
return remoteTokenServices;
|
return remoteTokenServices;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -67,8 +87,7 @@ public class ResourceServerConfig extends ResourceServerConfigurerAdapter
|
||||||
public void configure(HttpSecurity http) throws Exception
|
public void configure(HttpSecurity http) throws Exception
|
||||||
{
|
{
|
||||||
http.csrf().disable();
|
http.csrf().disable();
|
||||||
ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry = http
|
ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry = http.authorizeRequests();
|
||||||
.authorizeRequests();
|
|
||||||
// 不登录可以访问
|
// 不登录可以访问
|
||||||
authIgnoreConfig().getUrls().forEach(url -> registry.antMatchers(url).permitAll());
|
authIgnoreConfig().getUrls().forEach(url -> registry.antMatchers(url).permitAll());
|
||||||
registry.anyRequest().authenticated();
|
registry.anyRequest().authenticated();
|
||||||
|
|
@ -77,6 +96,7 @@ public class ResourceServerConfig extends ResourceServerConfigurerAdapter
|
||||||
@Override
|
@Override
|
||||||
public void configure(ResourceServerSecurityConfigurer resources)
|
public void configure(ResourceServerSecurityConfigurer resources)
|
||||||
{
|
{
|
||||||
|
resources.authenticationEntryPoint(getUnAuthorizedHandler()).accessDeniedHandler(customAccessDeniedHandler);
|
||||||
resources.tokenServices(tokenServices());
|
resources.tokenServices(tokenServices());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -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=\
|
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
|
||||||
com.ruoyi.common.security.service.UserDetailsServiceImpl,\
|
com.ruoyi.common.security.service.UserDetailsServiceImpl,\
|
||||||
|
com.ruoyi.common.security.service.CustomUserDetailsService,\
|
||||||
com.ruoyi.common.security.handler.CustomAccessDeniedHandler
|
com.ruoyi.common.security.handler.CustomAccessDeniedHandler
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -43,7 +43,7 @@ public class SwaggerProvider implements SwaggerResourcesProvider
|
||||||
.contains(routeDefinition.getId()))
|
.contains(routeDefinition.getId()))
|
||||||
.forEach(routeDefinition -> routeDefinition.getPredicates().stream()
|
.forEach(routeDefinition -> routeDefinition.getPredicates().stream()
|
||||||
.filter(predicateDefinition -> "Path".equalsIgnoreCase(predicateDefinition.getName()))
|
.filter(predicateDefinition -> "Path".equalsIgnoreCase(predicateDefinition.getName()))
|
||||||
.filter(predicateDefinition -> !"ruoyi-auth".equalsIgnoreCase(routeDefinition.getId()))
|
// .filter(predicateDefinition -> !"ruoyi-auth".equalsIgnoreCase(routeDefinition.getId()))
|
||||||
.forEach(predicateDefinition -> resourceList
|
.forEach(predicateDefinition -> resourceList
|
||||||
.add(swaggerResource(routeDefinition.getId(), predicateDefinition.getArgs()
|
.add(swaggerResource(routeDefinition.getId(), predicateDefinition.getArgs()
|
||||||
.get(NameUtils.GENERATED_NAME_PREFIX + "0").replace("/**", SWAGGER2URL)))));
|
.get(NameUtils.GENERATED_NAME_PREFIX + "0").replace("/**", SWAGGER2URL)))));
|
||||||
|
|
|
||||||
|
|
@ -21,7 +21,7 @@ import reactor.core.publisher.Mono;
|
||||||
@Component
|
@Component
|
||||||
public class ValidateCodeFilter extends AbstractGatewayFilterFactory<Object>
|
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
|
@Autowired
|
||||||
private ValidateCodeService validateCodeService;
|
private ValidateCodeService validateCodeService;
|
||||||
|
|
|
||||||
|
|
@ -29,7 +29,7 @@ spring:
|
||||||
eager: true
|
eager: true
|
||||||
transport:
|
transport:
|
||||||
# 控制台地址
|
# 控制台地址
|
||||||
dashboard: 127.0.0.1:8718
|
dashboard: 127.0.0.1:8076
|
||||||
# nacos配置持久化
|
# nacos配置持久化
|
||||||
datasource:
|
datasource:
|
||||||
ds1:
|
ds1:
|
||||||
|
|
|
||||||
|
|
@ -1,10 +1,14 @@
|
||||||
package com.ruoyi.system;
|
package com.ruoyi.system;
|
||||||
|
|
||||||
|
import com.ruoyi.common.core.domain.R;
|
||||||
import org.springframework.boot.SpringApplication;
|
import org.springframework.boot.SpringApplication;
|
||||||
import org.springframework.cloud.client.SpringCloudApplication;
|
import org.springframework.cloud.client.SpringCloudApplication;
|
||||||
import com.ruoyi.common.security.annotation.EnableCustomConfig;
|
import com.ruoyi.common.security.annotation.EnableCustomConfig;
|
||||||
import com.ruoyi.common.security.annotation.EnableRyFeignClients;
|
import com.ruoyi.common.security.annotation.EnableRyFeignClients;
|
||||||
import com.ruoyi.common.swagger.annotation.EnableCustomSwagger2;
|
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;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 系统模块
|
* 系统模块
|
||||||
|
|
@ -15,6 +19,7 @@ import com.ruoyi.common.swagger.annotation.EnableCustomSwagger2;
|
||||||
@EnableCustomSwagger2
|
@EnableCustomSwagger2
|
||||||
@EnableRyFeignClients
|
@EnableRyFeignClients
|
||||||
@SpringCloudApplication
|
@SpringCloudApplication
|
||||||
|
@ControllerAdvice
|
||||||
public class RuoYiSystemApplication
|
public class RuoYiSystemApplication
|
||||||
{
|
{
|
||||||
public static void main(String[] args)
|
public static void main(String[] args)
|
||||||
|
|
@ -31,4 +36,11 @@ public class RuoYiSystemApplication
|
||||||
" | | \\ / \\ / \n" +
|
" | | \\ / \\ / \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.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.security.access.prepost.PreAuthorize;
|
import org.springframework.security.access.prepost.PreAuthorize;
|
||||||
import org.springframework.validation.annotation.Validated;
|
import org.springframework.validation.annotation.Validated;
|
||||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
import org.springframework.web.bind.annotation.*;
|
||||||
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.multipart.MultipartFile;
|
import org.springframework.web.multipart.MultipartFile;
|
||||||
import com.ruoyi.common.core.constant.UserConstants;
|
import com.ruoyi.common.core.constant.UserConstants;
|
||||||
import com.ruoyi.common.core.domain.R;
|
import com.ruoyi.common.core.domain.R;
|
||||||
|
|
@ -117,6 +110,25 @@ public class SysUserController extends BaseController
|
||||||
return R.ok(sysUserVo);
|
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);
|
||||||
|
}
|
||||||
/**
|
/**
|
||||||
* 获取用户信息
|
* 获取用户信息
|
||||||
*
|
*
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
# Tomcat
|
# Tomcat
|
||||||
server:
|
server:
|
||||||
port: 9201
|
port: 9001
|
||||||
|
|
||||||
# Spring
|
# Spring
|
||||||
spring:
|
spring:
|
||||||
|
|
|
||||||
|
|
@ -37,8 +37,8 @@ const user = {
|
||||||
const uuid = userInfo.uuid
|
const uuid = userInfo.uuid
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
login(username, password, code, uuid).then(res => {
|
login(username, password, code, uuid).then(res => {
|
||||||
setToken(res.access_token)
|
setToken(res.data.access_token)
|
||||||
commit('SET_TOKEN', res.access_token)
|
commit('SET_TOKEN', res.data.access_token)
|
||||||
resolve()
|
resolve()
|
||||||
}).catch(error => {
|
}).catch(error => {
|
||||||
reject(error)
|
reject(error)
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue