黑马程序员技术交流社区
标题:
Spring Security的运用
[打印本页]
作者:
Mylo
时间:
2019-5-24 08:24
标题:
Spring Security的运用
Spring security是一个安全框架,下面,主要讲解Spring Security的一些运用,核心:
配置对应的路径以及访问该路径所需要的角色即可
package bs.lmy.auth;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import java.util.Collection;
import java.util.Iterator;
/**
* @program: test4Security
* @description:
* @author: lmy
* @create: 2019-01-04 10:42
*
* 判断当前用于的权限 以及 访问当前路径所需要的权限
**/
public class MyAccessDecisionManager implements AccessDecisionManager {
public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> collection) throws AccessDeniedException, InsufficientAuthenticationException {
Iterator<ConfigAttribute> iterator = collection.iterator();
System.err.println(iterator.hasNext() + " hasNext");
while(iterator.hasNext()){
ConfigAttribute attribute = iterator.next();
//访问所需要的权限
String attr = attribute.getAttribute();
System.err.println("当前需要的权限" + attr);
//当前用户所拥有的权限
Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
for (GrantedAuthority authority : authorities) {
System.err.println("当前拥有的权限" + authority.getAuthority());
if(authority.getAuthority().equals(attr)){
System.err.println("-----当前角色访问成功");
return ;
}
}
}
throw new AccessDeniedException("没有权限访问");
}
public boolean supports(ConfigAttribute configAttribute) {
return true;
}
public boolean supports(Class<?> aClass) {
return true;
}
}
package bs.lmy.auth;
import org.springframework.security.access.SecurityMetadataSource;
import org.springframework.security.access.intercept.AbstractSecurityInterceptor;
import org.springframework.security.access.intercept.InterceptorStatusToken;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import javax.servlet.*;
import java.io.IOException;
/**
* @program: test4Security
* @description: test
* @author: lmy
* @create: 2019-01-04 10:16
*
* 校验 权限
**/
public class MyFilter extends AbstractSecurityInterceptor implements Filter {
/**
*
*/
private FilterInvocationSecurityMetadataSource securityMetadataSource;
public void init(FilterConfig filterConfig) throws ServletException {
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
//封装request response chain
FilterInvocation filterInvocation = new FilterInvocation(request,response,chain);
InterceptorStatusToken token = super.beforeInvocation(filterInvocation);
try {
System.err.println("----放行");
filterInvocation.getChain().doFilter(filterInvocation.getRequest(),filterInvocation.getResponse());
}finally {
super.afterInvocation(token,null);
}
}
public void destroy() {
}
public Class<?> getSecureObjectClass() {
return FilterInvocation.class;
}
public SecurityMetadataSource obtainSecurityMetadataSource() {
return this.securityMetadataSource;
}
public FilterInvocationSecurityMetadataSource getSecurityMetadataSource() {
return securityMetadataSource;
}
public void setSecurityMetadataSource(FilterInvocationSecurityMetadataSource securityMetadataSource) {
this.securityMetadataSource = securityMetadataSource;
}
}
package bs.lmy.auth;
import bs.lmy.domain.Permission;
import bs.lmy.domain.Role;
import bs.lmy.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import java.util.*;
/**
* @program: test4Security
* @description:
* @author:lmy
* @create: 2019-01-04 10:33
*
* 定义 地址访问所需要的权限
*
* 这个类 它将所有的地址 以及 访问这个地址需要的角色绑定在一起
**/
public class MySecurityMetadataSource implements FilterInvocationSecurityMetadataSource {
private Map<String , Collection<ConfigAttribute>> map = new HashMap<String ,Collection<ConfigAttribute>>();
@Autowired
private PermissionService ps ;
//o 请求的地址
public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
List<Permission> list = ps.findPermissionAndRole();
for (Permission permission : list) {
List<Role> roles = permission.getRoleList();
if(roles.size() > 0){
Collection<ConfigAttribute> c1 = new ArrayList<ConfigAttribute>();
for (Role role : roles) {
ConfigAttribute s1 = new SecurityConfig(role.getRname());
c1.add(s1);
}
map.put(permission.getUrl(),c1);
}else{
Collection<ConfigAttribute> c1 = new ArrayList<ConfigAttribute>();
ConfigAttribute s1 = new SecurityConfig("ROLE_NONE");
c1.add(s1);
map.put(permission.getUrl(),c1);
}
}
/*List<Map<String, ArrayList<String>>> roleNameAndUrl = ps.findRoleNameAndUrl();
for (Map<String, ArrayList<String>> urlAndRoleName : roleNameAndUrl) {
Set<Map.Entry<String, ArrayList<String>>> entries = urlAndRoleName.entrySet();
Collection<ConfigAttribute> c1 = new ArrayList<ConfigAttribute>();
String url = "";
for (Map.Entry<String, ArrayList<String>> entry : entries) {
url = entry.getKey();
ArrayList<String> roleNames = entry.getValue();
for (String roleName : roleNames) {
ConfigAttribute s1 = new SecurityConfig(roleName);
c1.add(s1);
}
}
map.put(url,c1);
}*/
// System.err.println("访问的角色对应的地址" + roleNameAndUrl);
String requestUrl = ((FilterInvocation) o).getRequestUrl();
System.err.println("当前访问地址: " + requestUrl);
Set<String> urls = map.keySet();
for (String url : urls) {
if(requestUrl.contains(url)){
System.err.println("访问地址:" +url + "-----访问所拥有的权限---" +map.get(url));
return map.get(url);
}
}
/*Collection<ConfigAttribute> c1 = new ArrayList<ConfigAttribute>();
Collection<ConfigAttribute> c2= new ArrayList<ConfigAttribute>();
ConfigAttribute s1 = new SecurityConfig("ROLE_USER");
ConfigAttribute s2 = new SecurityConfig("ROLE_ADMIN");
c1.add(s1);
c2.add(s2);
map.put("/welcome**" , c1);
map.put("/admin**" , c2);
String url = ((FilterInvocation) o).getRequestUrl();
if(url.contains("welcome")){
return map.get("/welcome**");
}
if(url.contains("admin")){
return map.get("/admin**");
}*/
return null;
}
public Collection<ConfigAttribute> getAllConfigAttributes() {
return null;
}
public boolean supports(Class<?> aClass) {
return true;
}
}
package bs.lmy.auth;
import bs.lmy.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* @program: test4Security
* @description: test4springSecurity
* @author: lmy
* @create: 2019-01-04 10:06
*
* 验证
**/
public class MyUserDetailsService implements UserDetailsService {
@Autowired
private PermissionService ps;
@Autowired
HttpServletRequest request;
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
HttpSession session = request.getSession();
String username = ps.findUsernameByName(s);
session.setAttribute("username",username);
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
List<Map<String, Object>> list = ps.findUserNamePassWordAndRoleName();
for (Map<String, Object> map : list) {
Set<Map.Entry<String, Object>> entries = map.entrySet();
String password = "";
String roleName = "";
String name = "";
for (Map.Entry<String, Object> entry : entries) {
if(entry.getKey().equals("name")){
name = (String)entry.getValue();
}
if(entry.getKey().equals("password")){
password =(String) entry.getValue();
}
if(entry.getKey().equals("rname")){
roleName = (String)entry.getValue();
}
}
System.err.println("name" + s + "----" + name + "---" +roleName + "---" +password);
if(s.equals(name)){
authorities.add(new SimpleGrantedAuthority(roleName));
return new User(s,password,authorities);
}
}
return null;
}
}
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2