Skip to content
Open
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
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
Expand All @@ -49,7 +50,7 @@
* @see com.funtl.myshop.plus.business.configure
*/
@Configuration
@EnableAuthorizationServer
@EnableAuthorizationServer// 授权服务器核心注解
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {

@Autowired
Expand All @@ -64,6 +65,9 @@ public class AuthorizationServerConfiguration extends AuthorizationServerConfigu
@Autowired
private RedisConnectionFactory redisConnectionFactory;

@Autowired
private UserDetailsService userDetailsServiceBean;

@Bean
@Primary
@ConfigurationProperties(prefix = "spring.datasource")
Expand All @@ -85,19 +89,33 @@ public ClientDetailsService jdbcClientDetailsService() {
return new JdbcClientDetailsService(dataSource());
}

/**
* 声明授权和token的端点以及token的服务的一些配置信息,
* 比如采用什么存储方式、token的有效期等
*
* @param endpoints
*/
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints
// 用于支持密码模式
.authenticationManager(authenticationManager)
.tokenStore(tokenStore());
.tokenStore(tokenStore()).userDetailsService(userDetailsServiceBean);

}

/**
* 声明安全约束,哪些允许访问,哪些不允许访问
*
* @param security
*/
@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
security
// 允许客户端访问 /oauth/check_token 检查 token
.checkTokenAccess("isAuthenticated()")
.tokenKeyAccess("permitAll()")
// 允许表单认证
.allowFormAuthenticationForClients();
}

Expand All @@ -110,6 +128,21 @@ public void configure(AuthorizationServerSecurityConfigurer security) throws Exc
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
// 客户端配置
// 1. 数据库的方式
clients.withClientDetails(jdbcClientDetailsService());
// 2. 在内存中配置,这种方式不够灵活,学习倒是没有问题
// //配置两个客户端,一个用于password认证一个用于client认证
// clients.inMemory().withClient("client_1")
// .resourceIds(DEMO_RESOURCE_ID)
// .authorizedGrantTypes("client_credentials", "refresh_token")
// .scopes("select")
// .authorities("client")
// .secret("123456")
// .and().withClient("client_2")
// .resourceIds(DEMO_RESOURCE_ID)
// .authorizedGrantTypes("password", "refresh_token")
// .scopes("select")
// .authorities("client")
// .secret("123456");
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
//package com.funtl.myshop.plus.business.configure;
//
//import com.fasterxml.jackson.annotation.JsonAutoDetect;
//import com.fasterxml.jackson.annotation.PropertyAccessor;
//import com.fasterxml.jackson.databind.ObjectMapper;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.cache.CacheManager;
//import org.springframework.cache.annotation.CachingConfigurerSupport;
//import org.springframework.cache.annotation.EnableCaching;
//import org.springframework.cache.interceptor.KeyGenerator;
//import org.springframework.context.annotation.Bean;
//import org.springframework.context.annotation.Configuration;
//import org.springframework.data.redis.cache.RedisCacheManager;
//import org.springframework.data.redis.connection.RedisConnectionFactory;
//import org.springframework.data.redis.core.RedisTemplate;
//import org.springframework.data.redis.core.StringRedisTemplate;
//import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
//import org.springframework.data.redis.serializer.RedisSerializer;
//import org.springframework.data.redis.serializer.StringRedisSerializer;
//
//import java.lang.reflect.Method;
//
///**
// * @PackgeName: com.funtl.myshop.plus.business.configure
// * @ClassName: RedisConfig
// * @Author: Administrator
// * Date: 2019/12/1 0001 10:49
// * project name: MyShopPlus
// * @Version:
// * @Description:
// */
//@Configuration
//@EnableCaching
//public class RedisConfig extends CachingConfigurerSupport {
// @Autowired
// private RedisConnectionFactory factory;
// @Autowired
// private RedisSerializer fastJson2JsonRedisSerializer;
// @Bean
// public KeyGenerator keyGenerator() {
// return new KeyGenerator() {
// @Override
// public Object generate(Object target, Method method, Object... params) {
// StringBuilder sb = new StringBuilder();
// sb.append(target.getClass().getName());
// sb.append(method.getName());
// for (Object obj : params) {
// sb.append(obj.toString());
// }
// return sb.toString();
// }
// };
// }
//
// @SuppressWarnings("rawtypes")
// @Bean
// public CacheManager cacheManager(RedisTemplate redisTemplate) {
// RedisCacheManager rcm = new RedisCacheManager(redisTemplate);
// //设置缓存过期时间
// //rcm.setDefaultExpiration(60);//秒
// return rcm;
// }
//
//
// //fastjson
// @Bean(name="redisTemplate")
// public RedisTemplate<String, Object> fastJsonRedisTemplate() {
// RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
// template.setConnectionFactory(factory);
// //redis开启事务
// template.setEnableTransactionSupport(true);
// template.setKeySerializer(new StringRedisSerializer());
// template.setValueSerializer(fastJson2JsonRedisSerializer);
// template.setHashKeySerializer(new StringRedisSerializer());
// template.setHashValueSerializer(fastJson2JsonRedisSerializer);
// template.setDefaultSerializer(new StringRedisSerializer());
// template.afterPropertiesSet();
// return template;
// }
//
//}
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,8 @@ public AuthenticationManager authenticationManagerBean() throws Exception {
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring()
.antMatchers("/user/login");
.antMatchers("/user/login", "/user/resfresh_token","/oauth/check_token","/oauth/refresh_token");

}

@Override
Expand All @@ -75,7 +76,11 @@ protected void configure(HttpSecurity http) throws Exception {
*/
http.exceptionHandling()
.and()
// 不获取登录用户的 session
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
// .and()
// .authorizeRequests()
// .antMatchers("/oauth/**").permitAll();

// http.exceptionHandling()
// .and()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import com.funtl.myshop.plus.business.BusinessStatus;
import com.funtl.myshop.plus.business.dto.LoginInfo;
import com.funtl.myshop.plus.business.dto.LoginParam;
import com.funtl.myshop.plus.business.dto.OauthParam;
import com.funtl.myshop.plus.business.feign.ProfileFeign;
import com.funtl.myshop.plus.cloud.api.MessageService;
import com.funtl.myshop.plus.cloud.dto.UmsAdminLoginLogDTO;
Expand Down Expand Up @@ -55,6 +56,8 @@ public class LoginController {

@Value("${business.oauth2.grant_type}")
public String oauth2GrantType;
@Value("${business.oauth2.refresh_type}")
public String oauth2RefreshType;

@Value("${business.oauth2.client_id}")
public String oauth2ClientId;
Expand Down Expand Up @@ -112,7 +115,7 @@ public ResponseResult<Map<String, Object>> login(@RequestBody LoginParam loginPa
Map<String, Object> jsonMap = MapperUtils.json2map(jsonString);
String token = String.valueOf(jsonMap.get("access_token"));
result.put("token", token);

result.put("result",jsonMap);
// 发送登录日志
sendAdminLoginLog(userDetails.getUsername(), request);
} catch (Exception e) {
Expand All @@ -122,6 +125,35 @@ public ResponseResult<Map<String, Object>> login(@RequestBody LoginParam loginPa
return new ResponseResult<Map<String, Object>>(ResponseResult.CodeStatus.OK, "登录成功", result);
}

/**
* 登录
*
* @param oauthParam 登录参数
* @return {@link ResponseResult}
*/
@PostMapping(value = "/user/resfresh_token")
public ResponseResult<Map<String, Object>> resfresh_token(@RequestBody OauthParam oauthParam, HttpServletRequest request) throws Exception {
// 封装返回的结果集
Map<String, Object> result = Maps.newHashMap();
// 通过 HTTP 客户端请求登录接口
Map<String, String> params = Maps.newHashMap();
params.put("grant_type", oauth2RefreshType);
params.put("client_id", oauth2ClientId);
params.put("client_secret", oauth2ClientSecret);
params.put("refresh_token", oauthParam.getRefresh_token());
try {
// 解析响应结果封装并返回
Response response = OkHttpClientUtil.getInstance().postData(URL_OAUTH_TOKEN, params);
String jsonString = Objects.requireNonNull(response.body()).string();
Map<String, Object> jsonMap = MapperUtils.json2map(jsonString);
result.put("result", jsonMap);
} catch (Exception e) {
e.printStackTrace();
}
return new ResponseResult<Map<String, Object>>(ResponseResult.CodeStatus.OK, "刷新token成功", result);
}


/**
* 获取用户信息
*
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package com.funtl.myshop.plus.business.dto;

import lombok.Data;

import java.io.Serializable;

/**
* token参数
* <p>
* Description:
* </p>
*
* @author Lusifer
* @version v1.0.0
* @date 2019-07-29 11:13:56
* @see com.funtl.myshop.plus.business.dto
*/
@Data
public class OauthParam implements Serializable {

private String refresh_token;

}
Loading