spring security 3 自定义认证,授权示例
1,建一个web project,并导入所有需要的lib。
2,配置web.xml,使用Spring的机制装载:
- <?xml version="1.0" encoding="UTF-8"?>
- <web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
- http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
- <context-param>
- <param-name>contextConfigLocation</param-name>
- <param-value>classpath:applicationContext*.xml</param-value>
- </context-param>
- <listener>
- <listener-class>
- org.springframework.web.context.ContextLoaderListener
- </listener-class>
- </listener>
- <filter>
- <filter-name>springSecurityFilterChain</filter-name>
- <filter-class>
- org.springframework.web.filter.DelegatingFilterProxy
- </filter-class>
- </filter>
- <filter-mapping>
- <filter-name>springSecurityFilterChain</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
- <welcome-file-list>
- <welcome-file>login.jsp</welcome-file>
- </welcome-file-list>
- </web-app>
这个文件中的内容我相信大家都很熟悉了,不再多说了。
2,来看看applicationContext-security.xml这个配置文件,关于Spring Security的配置均在其中:
- <?xml version="1.0" encoding="UTF-8"?>
- <beans:beans xmlns="http://www.springframework.org/schema/security"
- xmlns:beans="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
- http://www.springframework.org/schema/security
- http://www.springframework.org/schema/security/spring-security-3.0.xsd">
- <http access-denied-page="/403.jsp"><!-- 当访问被拒绝时,会转到403.jsp -->
- <intercept-url pattern="/login.jsp" filters="none" />
- <form-login login-page="/login.jsp"
- authentication-failure-url="/login.jsp?error=true"
- default-target-url="/index.jsp" />
- <logout logout-success-url="/login.jsp" />
- <http-basic />
- <!-- 增加一个filter,这点与Acegi是不一样的,不能修改默认的filter了,这个filter位于FILTER_SECURITY_INTERCEPTOR之前 -->
- <custom-filter before="FILTER_SECURITY_INTERCEPTOR"
- ref="myFilter" />
- </http>
- <!-- 一个自定义的filter,必须包含authenticationManager,accessDecisionManager,securityMetadataSource三个属性,
- 我们的所有控制将在这三个类中实现,解释详见具体配置 -->
- <beans:bean id="myFilter" class="com.robin.erp.fwk.security.MyFilterSecurityInterceptor">
- <beans:property name="authenticationManager"
- ref="authenticationManager" />
- <beans:property name="accessDecisionManager"
- ref="myAccessDecisionManagerBean" />
- <beans:property name="securityMetadataSource"
- ref="securityMetadataSource" />
- </beans:bean>
- <!-- 认证管理器,实现用户认证的入口,主要实现UserDetailsService接口即可 -->
- <authentication-manager alias="authenticationManager">
- <authentication-provider
- user-service-ref="myUserDetailService">
- <!-- 如果用户的密码采用加密的话,可以加点“盐”
- <password-encoder hash="md5" />
- -->
- </authentication-provider>
- </authentication-manager>
- <beans:bean id="myUserDetailService"
- class="com.robin.erp.fwk.security.MyUserDetailService" />
- <!-- 访问决策器,决定某个用户具有的角色,是否有足够的权限去访问某个资源 -->
- <beans:bean id="myAccessDecisionManagerBean"
- class="com.robin.erp.fwk.security.MyAccessDecisionManager">
- </beans:bean>
- <!-- 资源源数据定义,即定义某一资源可以被哪些角色访问 -->
- <beans:bean id="securityMetadataSource"
- class="com.robin.erp.fwk.security.MyInvocationSecurityMetadataSource" />
- </beans:beans>
3,来看看自定义filter的实现:
- package com.example.spring.security;
- import java.io.IOException;
- import javax.servlet.Filter;
- import javax.servlet.FilterChain;
- import javax.servlet.FilterConfig;
- import javax.servlet.ServletException;
- import javax.servlet.ServletRequest;
- import javax.servlet.ServletResponse;
- 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;
- public class MyFilterSecurityInterceptor extends AbstractSecurityInterceptor
- implements Filter {
- private FilterInvocationSecurityMetadataSource securityMetadataSource;
- // ~ Methods
- // ========================================================================================================
- /**
- * Method that is actually called by the filter chain. Simply delegates to
- * the {@link #invoke(FilterInvocation)} method.
- *
- * @param request
- * the servlet request
- * @param response
- * the servlet response
- * @param chain
- * the filter chain
- *
- * @throws IOException
- * if the filter chain fails
- * @throws ServletException
- * if the filter chain fails
- */
- public void doFilter(ServletRequest request, ServletResponse response,
- FilterChain chain) throws IOException, ServletException {
- FilterInvocation fi = new FilterInvocation(request, response, chain);
- invoke(fi);
- }
- public FilterInvocationSecurityMetadataSource getSecurityMetadataSource() {
- return this.securityMetadataSource;
- }
- public Class<? extends Object> getSecureObjectClass() {
- return FilterInvocation.class;
- }
- public void invoke(FilterInvocation fi) throws IOException,
- ServletException {
- InterceptorStatusToken token = super.beforeInvocation(fi);
- try {
- fi.getChain().doFilter(fi.getRequest(), fi.getResponse());
- } finally {
- super.afterInvocation(token, null);
- }
- }
- public SecurityMetadataSource obtainSecurityMetadataSource() {
- return this.securityMetadataSource;
- }
- public void setSecurityMetadataSource(
- FilterInvocationSecurityMetadataSource newSource) {
- this.securityMetadataSource = newSource;
- }
- @Override
- public void destroy() {
- }
- @Override
- public void init(FilterConfig arg0) throws ServletException {
- }
- }
最核心的代码就是invoke方法中的InterceptorStatusToken token = super.beforeInvocation(fi);这一句,即在执行doFilter之前,进行权限的检查,而具体的实现已经交给accessDecisionManager了。
4,来看看authentication-provider的实现:
- package com.example.spring.security;
- import java.util.ArrayList;
- import java.util.Collection;
- import org.springframework.dao.DataAccessException;
- import org.springframework.security.core.GrantedAuthority;
- import org.springframework.security.core.authority.GrantedAuthorityImpl;
- 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;
- public class MyUserDetailService implements UserDetailsService {
- @Override
- public UserDetails loadUserByUsername(String username)
- throws UsernameNotFoundException, DataAccessException {
- Collection<GrantedAuthority> auths=new ArrayList<GrantedAuthority>();
- GrantedAuthorityImpl auth2=new GrantedAuthorityImpl("ROLE_ADMIN");
- auths.add(auth2);
- if(username.equals("robin1")){
- auths=new ArrayList<GrantedAuthority>();
- GrantedAuthorityImpl auth1=new GrantedAuthorityImpl("ROLE_ROBIN");
- auths.add(auth1);
- }
- // User(String username, String password, boolean enabled, boolean accountNonExpired,
- // boolean credentialsNonExpired, boolean accountNonLocked, Collection<GrantedAuthority> authorities) {
- User user = new User(username,
- "robin", true, true, true, true, auths);
- return user;
- }
- }
在这个类中,你就可以从数据库中读入用户的密码,角色信息,是否锁定,账号是否过期等,我想这么简单的代码就不再多解释了。
5,对于资源的访问权限的定义,我们通过实现FilterInvocationSecurityMetadataSource这个接口来初始化数据。
- package com.example.spring.security;
- import java.util.ArrayList;
- import java.util.Collection;
- import java.util.HashMap;
- import java.util.Iterator;
- import java.util.Map;
- 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.security.web.util.AntUrlPathMatcher;
- import org.springframework.security.web.util.UrlMatcher;
- /**
- *
- * 此类在初始化时,应该取到所有资源及其对应角色的定义
- *
- * @author Robin
- *
- */
- public class MyInvocationSecurityMetadataSource
- implements FilterInvocationSecurityMetadataSource {
- private UrlMatcher urlMatcher = new AntUrlPathMatcher();;
- private static Map<String, Collection<ConfigAttribute>> resourceMap = null;
- public MyInvocationSecurityMetadataSource() {
- loadResourceDefine();
- }
- private void loadResourceDefine() {
- resourceMap = new HashMap<String, Collection<ConfigAttribute>>();
- Collection<ConfigAttribute> atts = new ArrayList<ConfigAttribute>();
- ConfigAttribute ca = new SecurityConfig("ROLE_ADMIN");
- atts.add(ca);
- resourceMap.put("/index.jsp", atts);
- resourceMap.put("/i.jsp", atts);
- }
- // According to a URL, Find out permission configuration of this URL.
- public Collection<ConfigAttribute> getAttributes(Object object)
- throws IllegalArgumentException {
- // guess object is a URL.
- String url = ((FilterInvocation)object).getRequestUrl();
- Iterator<String> ite = resourceMap.keySet().iterator();
- while (ite.hasNext()) {
- String resURL = ite.next();
- if (urlMatcher.pathMatchesUrl(url, resURL)) {
- return resourceMap.get(resURL);
- }
- }
- return null;
- }
- public boolean supports(Class<?> clazz) {
- return true;
- }
- public Collection<ConfigAttribute> getAllConfigAttributes() {
- return null;
- }
- }
看看loadResourceDefine方法,我在这里,假定index.jsp和i.jsp这两个资源,需要ROLE_ADMIN角色的用户才能访问。
这个类中,还有一个最核心的地方,就是提供某个资源对应的权限定义,即getAttributes方法返回的结果。注意,我例子中使用的是AntUrlPathMatcher这个path matcher来检查URL是否与资源定义匹配,事实上你还要用正则的方式来匹配,或者自己实现一个matcher。
6,剩下的就是最终的决策了,make a decision,其实也很容易,呵呵。
- package com.example.spring.security;
- import java.util.Collection;
- import java.util.Iterator;
- 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;
- public class MyAccessDecisionManager implements AccessDecisionManager {
- //In this method, need to compare authentication with configAttributes.
- // 1, A object is a URL, a filter was find permission configuration by this URL, and pass to here.
- // 2, Check authentication has attribute in permission configuration (configAttributes)
- // 3, If not match corresponding authentication, throw a AccessDeniedException.
- public void decide(Authentication authentication, Object object,
- Collection<ConfigAttribute> configAttributes)
- throws AccessDeniedException, InsufficientAuthenticationException {
- if(configAttributes == null){
- return ;
- }
- System.out.println(object.toString()); //object is a URL.
- Iterator<ConfigAttribute> ite=configAttributes.iterator();
- while(ite.hasNext()){
- ConfigAttribute ca=ite.next();
- String needRole=((SecurityConfig)ca).getAttribute();
- for(GrantedAuthority ga:authentication.getAuthorities()){
- if(needRole.equals(ga.getAuthority())){ //ga is user's role.
- return;
- }
- }
- }
- throw new AccessDeniedException("no right");
- }
- @Override
- public boolean supports(ConfigAttribute attribute) {
- // TODO Auto-generated method stub
- return true;
- }
- @Override
- public boolean supports(Class<?> clazz) {
- return true;
- }
- }
在这个类中,最重要的是decide方法,如果不存在对该资源的定义,直接放行;否则,如果找到正确的角色,即认为拥有权限,并放行,否则throw new AccessDeniedException("no right");这样,就会进入上面提到的403.jsp页面
spring security 3 自定义认证,授权示例的更多相关文章
- Spring Security OAuth2.0认证授权三:使用JWT令牌
Spring Security OAuth2.0系列文章: Spring Security OAuth2.0认证授权一:框架搭建和认证测试 Spring Security OAuth2.0认证授权二: ...
- Spring Security OAuth2.0认证授权六:前后端分离下的登录授权
历史文章 Spring Security OAuth2.0认证授权一:框架搭建和认证测试 Spring Security OAuth2.0认证授权二:搭建资源服务 Spring Security OA ...
- Spring Security OAuth2.0认证授权二:搭建资源服务
在上一篇文章[Spring Security OAuth2.0认证授权一:框架搭建和认证测试](https://www.cnblogs.com/kuangdaoyizhimei/p/14250374. ...
- Spring Security OAuth2.0认证授权四:分布式系统认证授权
Spring Security OAuth2.0认证授权系列文章 Spring Security OAuth2.0认证授权一:框架搭建和认证测试 Spring Security OAuth2.0认证授 ...
- Spring Security OAuth2.0认证授权五:用户信息扩展到jwt
历史文章 Spring Security OAuth2.0认证授权一:框架搭建和认证测试 Spring Security OAuth2.0认证授权二:搭建资源服务 Spring Security OA ...
- Spring Security OAuth2.0认证授权一:框架搭建和认证测试
一.OAuth2.0介绍 OAuth(开放授权)是一个开放标准,允许用户授权第三方应用访问他们存储在另外的服务提供者上的信息,而不 需要将用户名和密码提供给第三方应用或分享他们数据的所有内容. 1.s ...
- Spring security OAuth2.0认证授权学习第四天(SpringBoot集成)
基础的授权其实只有两行代码就不单独写一个篇章了; 这两行就是上一章demo的权限判断; 集成SpringBoot SpringBoot介绍 这个篇章主要是讲SpringSecurity的,Spring ...
- Spring security OAuth2.0认证授权学习第三天(认证流程)
本来之前打算把第三天写基于Session认证授权的,但是后来视屏看完后感觉意义不大,而且内容简单,就不单独写成文章了; 简单说一下吧,就是通过Servlet的SessionApi 通过实现拦截器的前置 ...
- Spring security OAuth2.0认证授权学习第一天(基础概念-认证授权会话)
这段时间没有学习,可能是因为最近工作比较忙,每天回来都晚上11点多了,但是还是要学习的,进过和我的领导确认,在当前公司的技术架构方面,将持续使用Spring security,暂不做Shiro的考虑, ...
随机推荐
- PHP中 post 与get的区别 详细说明
1.Get 方法通过 URL 请求来传递用户的数据,将表单内各字段名称与其内容,以成对的字符串连接,置于 action 属性所指程序的 url 后,如[url]http://www.jincaib.c ...
- HashMap,HashTable ,LinkedHashMap,TreeMap的区别
Map:主要是存储键值对,不允许键重复,但可以值重复. HashMap:根据键的HashCode值来存储数据,根据键直接获取值.具有很快的访问速度,遍历时,取得的数据值的顺序都是随机的.hashMap ...
- Ajax的基本请求/响应模型
一.Ajax工作核心 Ajax的核心是JavaScript对象XMLHttpRequest(简称XHR).它是一种支持异步请求的技术.可以通过使用XHR对象向服务器提出请求并处理响应,而不阻塞用户. ...
- 微信小程序学习总结(1)
1.一个小程序文件最基本包含app.js.app.json.app.wxss和pages文件夹结构,pages中的页面必须要在app.json的pages项进行配置,app.json也提供窗口表现,t ...
- Java 泛型 协变性、逆变性
Java 泛型 协变性.逆变性 @author ixenos 摘要:协变性.协变通配符.协变数组.协变返回值 协变性.逆变性和无关性 在面向对象的计算机程序语言中,经常涉及到类型之间的转换,例如从具体 ...
- 3、Hibernate三态间的转换
学过hibernate的人都可能都知道hibernate有三种状态,transient(瞬时状态),persistent(持久化状态)以及detached(离线状态),大家伙也许也知道这三者之间的区别 ...
- Spring contextConfigLocation默认加载文件的位置
在使用Spring框架的时候,如果我们使用的是XML文件配置Bean的方式的话,我们往往会在web.xml里面配置如下内容: <context-param> <param-name& ...
- PHP7新功能及语法变化总结
1.标量类型声明有两种模式: 强制 (默认) 和 严格模式. 现在可以使用下列类型参数(无论用强制模式还是严格模式): 字符串(string), 整数 (int), 浮点数 (float), 以及布尔 ...
- js与jquery实时监听输入框值变化方法
本文实例讲述了js与jquery实时监听输入框值的oninput与onpropertychange方法.分享给大家供大家参考.具体如下: 最近做过一个项目,需求是下拉框里自动匹配关键字,具体细节是实时 ...
- SqlServer 汉字转换拼音首字母函数
CREATE function [dbo].[Func_GetPY](@str nvarchar(4000))returns nvarchar(4000)asbegin set @str=RTRIM( ...