This commit is contained in:
APLS 2020-08-24 02:16:44 +08:00
parent b009fb792a
commit bd37012c3e
6 changed files with 43 additions and 22 deletions

View File

@ -31,18 +31,22 @@ import java.util.Map;
public class SecurityAuthenticationHandler implements AuthenticationSuccessHandler, AuthenticationFailureHandler , LogoutSuccessHandler { public class SecurityAuthenticationHandler implements AuthenticationSuccessHandler, AuthenticationFailureHandler , LogoutSuccessHandler {
@Autowired @Autowired
RedisUtil redisUtil; RedisUtil redisUtil;
@Value("${redis.user.token}")
String token_;
private static Gson gson = new Gson();
@Override @Override
public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException { public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
UsernamePasswordAuthenticationToken at = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication(); UsernamePasswordAuthenticationToken at = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
Gson gson = new Gson();
httpServletResponse.setContentType("application/json;charset=utf-8"); httpServletResponse.setContentType("application/json;charset=utf-8");
PrintWriter writer = httpServletResponse.getWriter(); PrintWriter writer = httpServletResponse.getWriter();
Map<String, Object> token = new HashMap<>(); Map<String, Object> token = new HashMap<>();
token.put("token", at.getToken()); token.put("token", at.getToken());
token.put("username", at.getName()); token.put("username", at.getName());
token.put("authority", at.getAuthority()); token.put("authority", at.getAuthority());
token.put("expire", (int) redisUtil.getExpire("token:" + at.getToken())); token.put("expire", redisUtil.getExpire(token_ + at.getToken()));
writer.write(gson.toJson(ResultUtil.success(token)) ); writer.write(gson.toJson(ResultUtil.success(token)) );
writer.flush(); writer.flush();
} }
@ -51,7 +55,7 @@ public class SecurityAuthenticationHandler implements AuthenticationSuccessHandl
public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException { public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
httpServletResponse.setContentType("application/json;charset=utf-8"); httpServletResponse.setContentType("application/json;charset=utf-8");
PrintWriter writer = httpServletResponse.getWriter(); PrintWriter writer = httpServletResponse.getWriter();
writer.write("Failure"); writer.write(gson.toJson(ResultUtil.error(-1, "failed!")));
writer.flush(); writer.flush();
} }

View File

@ -44,6 +44,8 @@ public class UrlAccessDecisionManager implements AccessDecisionManager {
Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities(); Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
for (GrantedAuthority ga : authorities) { for (GrantedAuthority ga : authorities) {
if (needPermission.equals(ga.getAuthority())) { if (needPermission.equals(ga.getAuthority())) {
log.info("当前角色: " + ga.getAuthority());
log.info("访问 " + o.toString() + " 已授权!");
return; return;
} }
} }

View File

@ -1,6 +1,7 @@
package io.qyi.e5.config.security; package io.qyi.e5.config.security;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.ConfigAttribute; import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig; import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation; import org.springframework.security.web.FilterInvocation;
@ -21,6 +22,13 @@ import java.util.*;
@Service @Service
public class UrlInvocationSecurityMetadataSourceService implements FilterInvocationSecurityMetadataSource { public class UrlInvocationSecurityMetadataSourceService implements FilterInvocationSecurityMetadataSource {
@Value("web.security.admin")
private String[] securityAdmin;
@Value("web.security.user")
private String[] securityUser;
@Value("web.security.role_anonymous")
private String[] securitAnonymous;
private HashMap<String, Collection<ConfigAttribute>> map =null; private HashMap<String, Collection<ConfigAttribute>> map =null;
/** /**
* 加载权限表中所有权限 * 加载权限表中所有权限
@ -31,22 +39,22 @@ public class UrlInvocationSecurityMetadataSourceService implements FilterInvocat
map = new HashMap<>(); map = new HashMap<>();
Collection<ConfigAttribute> array; Collection<ConfigAttribute> array;
ConfigAttribute cfg; ConfigAttribute cfg;
Map<String, String> permissions = new HashMap<>(); Map<String, String []> permissions = new HashMap<>();
/*这里只是简单的配置*/ /*这里只是简单的配置*/
permissions.put("/admin/**", "admin"); permissions.put("admin", securityAdmin);
permissions.put("/**", "user"); permissions.put("user", securityUser);
permissions.put("/auth2/**", "ROLE_ANONYMOUS"); permissions.put("ROLE_ANONYMOUS", securitAnonymous);
permissions.put("/error", "ROLE_ANONYMOUS");
Iterator<Map.Entry<String, String>> iterator = permissions.entrySet().iterator(); Iterator<Map.Entry<String, String[]>> iterator = permissions.entrySet().iterator();
while (iterator.hasNext()) { while (iterator.hasNext()) {
Map.Entry<String, String> next = iterator.next(); Map.Entry<String, String[]> next = iterator.next();
String key = next.getKey(); String key = next.getKey();
String value = next.getValue(); String[] value = next.getValue();
array = new ArrayList<>(); array = new ArrayList<>();
cfg = new SecurityConfig(value); for (int i = 0; i < value.length; i++) {
array.add(cfg); cfg = new SecurityConfig(value[i]);
array.add(cfg);
}
map.put(key, array); map.put(key, array);
} }

View File

@ -67,7 +67,7 @@ public class UsernamePasswordAuthenticationProvider implements AuthenticationPro
List<String> list = new ArrayList<>(); List<String> list = new ArrayList<>();
list.add("admin"); list.add("admin");
list.add("user"); list.add("user");
String[] l =list.toArray(new String[list.size()]); String[] l = list.toArray(new String[list.size()]);
String token = EncryptUtil.getInstance().SHA1Hex(UUID.randomUUID().toString()); String token = EncryptUtil.getInstance().SHA1Hex(UUID.randomUUID().toString());
UsernamePasswordAuthenticationToken authenticationToken1 = new UsernamePasswordAuthenticationToken("debugName", UsernamePasswordAuthenticationToken authenticationToken1 = new UsernamePasswordAuthenticationToken("debugName",
"DebugAvatar", adminGithubId, token, "admin", AuthorityUtils.createAuthorityList(l)); "DebugAvatar", adminGithubId, token, "admin", AuthorityUtils.createAuthorityList(l));
@ -114,23 +114,23 @@ public class UsernamePasswordAuthenticationProvider implements AuthenticationPro
String token = EncryptUtil.getInstance().SHA1Hex(UUID.randomUUID().toString()); String token = EncryptUtil.getInstance().SHA1Hex(UUID.randomUUID().toString());
/*配置角色,这里只是简单的配置,实际上需要从数据库中读取角色*/ /*配置角色,这里只是简单的配置,实际上需要从数据库中读取角色*/
List<String> list = new ArrayList<>(); List<String> list_Authority = new ArrayList<>();
list.add("user"); list_Authority.add("user");
if (adminGithubId == github.getGithubId()) { if (adminGithubId == github.getGithubId()) {
list.add("admin"); list_Authority.add("admin");
} }
String[] Authority =list.toArray(new String[list.size()]); String[] Authority = list_Authority.toArray(new String[list_Authority.size()]);
/*写token信息到redis*/ /*写token信息到redis*/
userInfo_redis.put("github_name", github.getName()); userInfo_redis.put("github_name", github.getName());
userInfo_redis.put("github_id", github.getGithubId()); userInfo_redis.put("github_id", github.getGithubId());
userInfo_redis.put("avatar_url", github.getAvatarUrl()); userInfo_redis.put("avatar_url", github.getAvatarUrl());
userInfo_redis.put("authority", Authority); userInfo_redis.put("authority", list_Authority);
redisUtil.hmset(token_ + token, userInfo_redis, tokenExpire); redisUtil.hmset(token_ + token, userInfo_redis, tokenExpire);
// 创建一个已认证的token // 创建一个已认证的token
UsernamePasswordAuthenticationToken authenticationToken1 = new UsernamePasswordAuthenticationToken(github.getName(), UsernamePasswordAuthenticationToken authenticationToken1 = new UsernamePasswordAuthenticationToken(github.getName(),
github.getAvatarUrl(), github.getGithubId() , AuthorityUtils.createAuthorityList(Authority)); github.getAvatarUrl(), github.getGithubId(), token, "user", AuthorityUtils.createAuthorityList(Authority));
// 设置一些详细信息 // 设置一些详细信息
authenticationToken1.setDetails(authenticationToken); authenticationToken1.setDetails(authenticationToken);

View File

@ -59,7 +59,6 @@ public class AdminController {
} }
@GetMapping("/test") @GetMapping("/test")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public String test() { public String test() {
return "ok"; return "ok";
} }

View File

@ -0,0 +1,8 @@
/**
* @program: e5
* @description:
* @author: 落叶随风
* @create: 2020-08-10 02:10
**/
public class httptest {
}