Spring security权限配置与使用大全

网友投稿 922 2022-12-07

Spring security权限配置与使用大全

Spring security权限配置与使用大全

简介

Spring Security 是为了基于Spring的应用程序提供的声明式安全保护的安全性框架。Spring Security 提供了完整的安全性解决方案,它能够在Web请求级别和方法调用级别处理身份认证和授权。因为基于Spring框架,所以SPring Security充分使用了一览注入和面向切面技术。

Spring Security 本质上是借助一系列的 Servlet Filter来提供各种安全性功能,但这并不需要我们手动去添加或者创建多个Filter。实际上,我们仅需要配置一个Filter即可。

DelegatingFilterProxy 是一个特殊的Filter,他本身并没有做太多工作,而是将工作委托给了一个注入到Spring应用上下文的Filter实现类。

在本例中,主要讲解spring-security的配置与使用,实现方式为:

1.将用户、权限、资源(url)采用数据库存储

2.自定义过滤器,代替原有的 FilterSecurityInterceptor

3.自定义实现 UserDetailsService、Filter、AccessDecisionManager和FilterInvocationSecurityMetadataSource并在配置文件进行相应的配置

4.Spring-seculity在自定义用户验证的类加载必须早于Controller层创建

1.配置Spring-seculity.xml

xmlns:security="http://springframework.org/schema/security"

xmlns:xsi="http://w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://springframework.org/schema/beans

http://springframework.org/schema/beans/spring-beans.xsd

http://springframework.org/schema/security

http://springframework.org/schema/security/spring-security.xsd">

username-parameter="username" password-parameter="password"

authentication-failure-url="/filer.jsp" default-target-url="/jsp/all-admin-index.jsp"/>

xmlns:security="http://springframework.org/schema/security"

xmlns:xsi="http://w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://springframework.org/schema/beans

http://springframework.org/schema/beans/spring-beans.xsd

http://springframework.org/schema/security

http://springframework.org/schema/security/spring-security.xsd">

username-parameter="username" password-parameter="password"

authentication-failure-url="/filer.jsp" default-target-url="/jsp/all-admin-index.jsp"/>

username-parameter="username" password-parameter="password"

authentication-failure-url="/filer.jsp" default-target-url="/jsp/all-admin-index.jsp"/>

2.配置Web.xml

xmlns:xsi="http://w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"

version="4.0">

ssm-web

all-admin-login.jsp

index.htm

index.jsp

default.html

default.htm

default.jsp

contextConfigLocation

classpath:ApplicantContext.xml,classpath:spring-security.xml

org.springframework.web.context.ContextLoaderListener

springSecurityFilterChain

org.springframework.web.filter.DelegatingFilterProxy

springSecurityFilterChain

/*

DispatcherServlet

org.springframework.web.servlet.DispatcherServlet

contextConfigLocation

classpath:spring-mvc.xml

1

DispatcherServlet

/

CharacterEncodingFilter

org.springframework.web.filter.CharacterEncodingFilter

encoding

UTF-8

CharacterEncodingFilter

/*

xmlns:xsi="http://w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"

version="4.0">

ssm-web

all-admin-login.jsp

index.htm

index.jsp

default.html

default.htm

default.jsp

contextConfigLocation

classpath:ApplicantContext.xml,classpath:spring-security.xml

org.springframework.web.context.ContextLoaderListener

springSecurityFilterChain

org.springframework.web.filter.DelegatingFilterProxy

springSecurityFilterChain

/*

DispatcherServlet

org.springframework.web.servlet.DispatcherServlet

contextConfigLocation

classpath:spring-mvc.xml

1

DispatcherServlet

/

CharacterEncodingFilter

org.springframework.web.filter.CharacterEncodingFilter

encoding

UTF-8

CharacterEncodingFilter

/*

3.自定义用户角色验证

package ssm.service;

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.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 org.springframework.stereotype.Service;

import ssm.bean.Role;

import ssm.bean.UserInfo;

import ssm.dao.LoginDao;

import java.util.ArrayList;

import java.util.List;

@Service("userinfo")

public class UserinfoService implements IUserInfoService{

@Autowired

LoginDao loginDao;

@Override

public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {    //将s传参从数据库查询是否用这个用户

UserInfo info=loginDao.findByList(s);

List list=info.getRoles();

List role= new ArrayList();

for(Role i:list){

role.add(new SimpleGrantedAuthority("ROLE_"+i.getRolename()));

}

System.out.println(s);

return new User(info.getUsername(), "{noop}"+info.getPassword(),info.getStatus()!=0?true:false,true,true,true, role);

}

}

4.seculity自定义过滤器

package filter;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.core.annotation.Order;

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.stereotype.Component;

import org.springframework.stereotype.Service;

import javax.servlet.*;

import java.io.IOException;

@Service("myFilter")

public class MyFilter extends AbstractSecurityInterceptor implements Filter {

@Autowired

private FilterInvocationSecurityMetadataSource securityMetadataSource;

@Override

public Class> getSecureObjectClass() {

return FilterInvocation.class;

}

@Override

public SecurityMetadataSource obtainSecurityMetadataSource() {

return securityMetadataSource;

}

@Autowired

public void setMyAccessDecisionManager(MyAccessDescisionManager myAccessDescisionManager) {

super.setAccessDecisionManager(myAccessDescisionManager);

}

@Override

public void init(FilterConfig filterConfig) throws ServletException {

}

@Override

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)

throws IOException, ServletException {

System.out.println("------------MyFilterSecurityInterceptor.doFilter()-----------开始-了....");

FilterInvocation fi = new FilterInvocation(request, response, chain);

InterceptorStatusToken token = super.beforeInvocation(fi);

try {

fi.getChain().doFilter(fi.getRequest(), fi.getResponse());

} catch (Exception e) {

e.printStackTrace();

} finally {

super.afterInvocation(token, null);

}

System.out.println("------------MyFilterSecurityInterceptor.doFilter()------------该方法结束了....");

}

@Override

public void destroy() {

}

}

5.自定义用户权限验证

package filter;

import org.springframework.security.access.AccessDecisionManager;

import org.springframework.security.access.AccessDeniedException;

import org.springframework.security.access.ConfigAttribute;

import org.springframework.security.authentication.InsufficientAuthenticationException;

import org.springframework.security.core.Authentication;

import org.springframework.security.core.GrantedAuthority;

import org.springframework.stereotype.Component;

import org.springframework.stereotype.Service;

import java.util.Collection;

import java.util.Iterator;

@Service

public class MyAccessDescisionManager implements AccessDecisionManager {

@Override

public void decide(Authentication authentication, Object object, Collection configAttributes)throws AccessDeniedException, InsufficientAuthenticationException {

// TODO Auto-generated method stub

System.out.println("MyAccessDescisionManager.decide()------------------验证用户是否具有一定的权限--------");

if(configAttributes==null) return;

Iterator it = configAttributes.iterator();

while(it.hasNext()){

String needResource = it.next().getAttribute();

//authentication.getAuthorities() 用户所有的权限

for(GrantedAuthority ga:authentication.getAuthorities()){

System.out.println("ROLE_"+needResource);

System.out.println(ga.getAuthority());

if(("ROLE_"+needResource).equals(ga.getAuthority())){

return;

}

}

}

throw new AccessDeniedException("--------MyAccessDescisionManager:decide-------权限认证失败!");

}

@Override

public boolean supports(ConfigAttribute attribute) {

// TODO Auto-generated method stub

return true;

}

@Override

public boolean supports(Class> clazz) {

// TODO Auto-generated method stub

return true;

}

}

6.自定义初始化用户角色和权限属性

package filter;

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 org.springframework.stereotype.Component;

import org.springframework.stereotype.Service;

import org.springframework.util.AntPathMatcher;

import ssm.bean.Premission;

import ssm.bean.Role;

import ssm.dao.LoginDao;

import ssm.dao.MapperRoleDao;

import ssm.dao.MapperUserDao;

import java.util.*;

@Service

public class MySecurityMetadataSource implements FilterInvocationSecurityMetadataSource {

/*@Autowired

private IUserDao userDao; */

@Autowired

private LoginDao loginDao;

/* 保存资源和权限的对应关系 key-资源url value-权限 */

private static Map> resourceMap = null;

private AntPathMatcher urlMatcher = new AntPathMatcher();

public MySecurityMetadataSource() {

//loadResourcesDefine();

}

@Override

public Collection getAllConfigAttributes() {

return null;

}

private void loadResourcesDefine(){

resourceMap = new HashMap>();

CvOFOR System.out.println("MySecurityMetadataSource.loadResourcesDefine()--------------开始加载资源列表数据--------");

List roles;

try {

roles = loginDao.findByROleList();

for(Role role : roles){

List permissions = role.getPremission();

for(Premission permission : permissions){

Collection configAttributes = null;

ConfigAttribute configAttribute = new SecurityConfig(role.getRolename());

if(resourceMap.containsKey(permission.getUrl())){

configAttributes = resourceMap.get(permission.getUrl());

configAttributes.add(configAttribute);

}else{

configAttributes = new ArrayList() ;

configAttributes.add(configAttribute);

resourceMap.put(permission.getUrl(), configAttributes);

}

}

}

System.out.println("11");

Set set = resourceMap.keySet();

Iterator it = set.iterator();

int i=0;

while(it.hasNext()){

String s = it.next();

System.out.println(++i+"key:"+s+"|value:"+resourceMap.get(s));

}

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

/*

* 根据请求的资源地址,获取它所拥有的权限

*/

@Override

public Collection getAttributes(Object obj)

throws IllegalArgumentException {

if(null==resourceMap||resourceMap.size() == 0) {

loadResourcesDefine();

}

//获取请求的url地址

String url = ((FilterInvocation)obj).getRequestUrl();

System.out.println("MySecurityMetadataSource:getAttributes()---------------请求地址为:"+url);

Iterator it = resourceMap.keySet().iterator();

while(it.hasNext()){

String _url = it.next();

if(url.indexOf("?")!=-1){

url = url.substring(0, url.indexOf("?"));

}

if(urlMatcher.match(_url,url)){

System.out.println("MySecurityMetadataSource:getAttributes()---------------需要的权限是:"+resourceMap.get(_url));

return resourceMap.get(_url);

}

}

Collection nouse = new ArrayList();

nouse.add(new SecurityConfig("无相应权限"));

return nouse;

}

@Override

public boolean supports(Class> arg0) {

System.out.println("MySecurityMetadataSource.supports()---------------------");

return true;

}

}

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:基于springboot拦截器HandlerInterceptor的注入问题
下一篇:Spring boot项目整合WebSocket方法
相关文章

 发表评论

暂时没有评论,来抢沙发吧~