Commit 8c35e106 authored by maqing's avatar maqing

RSA密码加密

parent 0ff5381a
package com.hungraim.ltc.controller;
import com.hungraim.ltc.redis.RedisCache;
import com.hungraim.ltc.util.CsoftSecurityUtil;
import com.hungraim.ltc.util.Result;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.Principal;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
* 认证中心
......@@ -26,6 +32,8 @@ import java.util.Map;
@AllArgsConstructor
public class AuthController {
private final RedisCache redisCache;
private final TokenEndpoint tokenEndpoint;
@PostMapping("/token")
......@@ -35,6 +43,8 @@ public class AuthController {
String decrypt = CsoftSecurityUtil.decryptRSADefault(password);
parameters.put("password", decrypt);
OAuth2AccessToken oAuth2AccessToken = tokenEndpoint.postAccessToken(principal, parameters).getBody();
// redisCache.setCacheObject("token", oAuth2AccessToken.getValue());
return Result.success(oAuth2AccessToken);
}
......@@ -48,15 +58,9 @@ public class AuthController {
return Result.success(keyMap.get(0).toString());
}
@GetMapping("/authLogout")
public Result authLogout(HttpServletRequest request, HttpServletResponse response) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
//清除认证
if (auth != null) {
new SecurityContextLogoutHandler().logout(request, response, auth);
}
@GetMapping("/logout")
public Result doLogout(){
return Result.success();
}
}
......@@ -66,6 +66,16 @@ public class AuthorizationServerConfiguration extends AuthorizationServerConfigu
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.withClientDetails(clientDetails());
clients.inMemory()
.withClient("password")
/*
* 表示OAuth 2中的授权模式为“password”和“refresh_token”两种
* 在标准的OAuth 2协议中,授权模式并不包括“refresh_token”,但是在Spring Security的实现中将其归为一种,
* 因此如果要实现access_token的刷新,就需要添加这样一种授权模式
*/
.authorizedGrantTypes("password", "refresh_token")
.accessTokenValiditySeconds(1800); // 配置了access_token的过期时间
}
/**
......
......@@ -12,6 +12,7 @@ import org.springframework.security.config.annotation.web.configuration.WebSecur
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
......@@ -23,6 +24,7 @@ import org.springframework.security.web.authentication.logout.SecurityContextLog
@EnableGlobalMethodSecurity(prePostEnabled = true,securedEnabled = true)
@Order(1)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
LogoutSuccessHandler logoutSuccessHandlerl;
/**
* 配置用户的安全拦截策略
......@@ -35,13 +37,14 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
.authorizeRequests().requestMatchers(EndpointRequest.toAnyEndpoint()).permitAll()
.and()
.authorizeRequests()
.antMatchers("/getPublicKey","/oauth/*").permitAll()
.anyRequest().authenticated()
.and()
.logout()
.logoutUrl("/oauth/logout")
.invalidateHttpSession(true);
.antMatchers("/getPublicKey","/oauth/*","/logout").permitAll()
.anyRequest().authenticated();
http.logout()
.logoutSuccessUrl("http://localhost:8000/oauth/logout")
.invalidateHttpSession(true)
.clearAuthentication(true)
.permitAll();
http.formLogin();
}
/**
......
package com.hungraim.ltc.redis;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundSetOperations;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import java.util.*;
import java.util.concurrent.TimeUnit;
/**
* @author mq
*/
@SuppressWarnings(value = { "unchecked", "rawtypes" })
@Component
public class RedisCache
{
@Autowired
public RedisTemplate redisTemplate;
/**
* 缓存基本的对象,Integer、String、实体类等
*
* @param key 缓存的键值
* @param value 缓存的值
*/
public <T> void setCacheObject(final String key, final T value)
{
redisTemplate.opsForValue().set(key, value);
}
/**
* 缓存基本的对象,Integer、String、实体类等
*
* @param key 缓存的键值
* @param value 缓存的值
* @param timeout 时间
* @param timeUnit 时间颗粒度
*/
public <T> void setCacheObject(final String key, final T value, final Integer timeout, final TimeUnit timeUnit)
{
redisTemplate.opsForValue().set(key, value, timeout, timeUnit);
}
/**
* 设置有效时间
*
* @param key Redis键
* @param timeout 超时时间
* @return true=设置成功;false=设置失败
*/
public boolean expire(final String key, final long timeout)
{
return expire(key, timeout, TimeUnit.SECONDS);
}
/**
* 设置有效时间
*
* @param key Redis键
* @param timeout 超时时间
* @param unit 时间单位
* @return true=设置成功;false=设置失败
*/
public boolean expire(final String key, final long timeout, final TimeUnit unit)
{
return redisTemplate.expire(key, timeout, unit);
}
/**
* 获得缓存的基本对象。
*
* @param key 缓存键值
* @return 缓存键值对应的数据
*/
public <T> T getCacheObject(final String key)
{
ValueOperations<String, T> operation = redisTemplate.opsForValue();
return operation.get(key);
}
/**
* 删除单个对象
*
* @param key
*/
public boolean deleteObject(final String key)
{
return redisTemplate.delete(key);
}
/**
* 删除集合对象
*
* @param collection 多个对象
* @return
*/
public long deleteObject(final Collection collection)
{
return redisTemplate.delete(collection);
}
/**
* 缓存List数据
*
* @param key 缓存的键值
* @param dataList 待缓存的List数据
* @return 缓存的对象
*/
public <T> long setCacheList(final String key, final List<T> dataList)
{
Long count = redisTemplate.opsForList().rightPushAll(key, dataList);
return count == null ? 0 : count;
}
/**
* 获得缓存的list对象
*
* @param key 缓存的键值
* @return 缓存键值对应的数据
*/
public <T> List<T> getCacheList(final String key)
{
return redisTemplate.opsForList().range(key, 0, -1);
}
/**
* 缓存Set
*
* @param key 缓存键值
* @param dataSet 缓存的数据
* @return 缓存数据的对象
*/
public <T> BoundSetOperations<String, T> setCacheSet(final String key, final Set<T> dataSet)
{
BoundSetOperations<String, T> setOperation = redisTemplate.boundSetOps(key);
Iterator<T> it = dataSet.iterator();
while (it.hasNext())
{
setOperation.add(it.next());
}
return setOperation;
}
/**
* 获得缓存的set
*
* @param key
* @return
*/
public <T> Set<T> getCacheSet(final String key)
{
return redisTemplate.opsForSet().members(key);
}
/**
* 缓存Map
*
* @param key
* @param dataMap
*/
public <T> void setCacheMap(final String key, final Map<String, T> dataMap)
{
if (dataMap != null) {
redisTemplate.opsForHash().putAll(key, dataMap);
}
}
/**
* 获得缓存的Map
*
* @param key
* @return
*/
public <T> Map<String, T> getCacheMap(final String key)
{
return redisTemplate.opsForHash().entries(key);
}
/**
* 往Hash中存入数据
*
* @param key Redis键
* @param hKey Hash键
* @param value 值
*/
public <T> void setCacheMapValue(final String key, final String hKey, final T value)
{
redisTemplate.opsForHash().put(key, hKey, value);
}
/**
* 获取Hash中的数据
*
* @param key Redis键
* @param hKey Hash键
* @return Hash中的对象
*/
public <T> T getCacheMapValue(final String key, final String hKey)
{
HashOperations<String, String, T> opsForHash = redisTemplate.opsForHash();
return opsForHash.get(key, hKey);
}
/**
* 删除Hash中的数据
*
* @param key
* @param hkey
*/
public void delCacheMapValue(final String key, final String hkey)
{
HashOperations hashOperations = redisTemplate.opsForHash();
hashOperations.delete(key, hkey);
}
/**
* 获取多个Hash中的数据
*
* @param key Redis键
* @param hKeys Hash键集合
* @return Hash对象集合
*/
public <T> List<T> getMultiCacheMapValue(final String key, final Collection<Object> hKeys)
{
return redisTemplate.opsForHash().multiGet(key, hKeys);
}
/**
* 获得缓存的基本对象列表
*
* @param pattern 字符串前缀
* @return 对象列表
*/
public Collection<String> keys(final String pattern)
{
return redisTemplate.keys(pattern);
}
}
\ No newline at end of file
......@@ -51,7 +51,7 @@ public class ResourceServerConfig {
http.oauth2ResourceServer().jwt()
.jwtAuthenticationConverter(jwtAuthenticationConverter());
http.authorizeExchange()
.pathMatchers("/api/oauth/token","/oauth/*","/api/oauth/genKeyPair").permitAll()
.pathMatchers("/api/oauth/token","/oauth/token","/oauth/*","/api/oauth/genKeyPair","/logout").permitAll()
.anyExchange().access(authorizationManager)
.and()
.exceptionHandling()
......@@ -61,6 +61,7 @@ public class ResourceServerConfig {
.authenticationEntryPoint(authenticationEntryPoint())
.and().csrf().disable();
return http.build();
}
......
......@@ -4,6 +4,7 @@ package com.hungraim.ltc.gateway.security;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.hungraim.ltc.constant.AuthConstants;
import com.hungraim.ltc.redis.RedisCache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
......@@ -35,6 +36,8 @@ public class AuthorizationManager implements ReactiveAuthorizationManager<Author
private final RedisTemplate redisTemplate;
private RedisCache redisCache;
@Autowired
public AuthorizationManager(RedisTemplate redisTemplate) {
this.redisTemplate = redisTemplate;
......@@ -45,6 +48,7 @@ public class AuthorizationManager implements ReactiveAuthorizationManager<Author
public Mono<AuthorizationDecision> check(Mono<Authentication> mono, AuthorizationContext authorizationContext) {
ServerHttpRequest request = authorizationContext.getExchange().getRequest();
String path = request.getMethodValue() + "_" + request.getURI().getPath();
log.info("请求,path={}", path);
......@@ -63,6 +67,12 @@ public class AuthorizationManager implements ReactiveAuthorizationManager<Author
return Mono.just(new AuthorizationDecision(false));
}
// String tokenRedis = redisCache.getCacheObject("token");
// if (StrUtil.isBlank(tokenRedis)) {
// log.info("请求token为空拒绝访问,path={}", path);
// return Mono.just(new AuthorizationDecision(false));
// }
// 从缓存取资源权限角色关系列表
Map<Object, Object> permissionRoles = redisTemplate.opsForHash().entries(AuthConstants.PERMISSION_ROLES_KEY);
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment