spring security 3 简单例子(自定义权限)

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
	id="WebApp_ID" version="3.0">

	<display-name>spring3</display-name>

	<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>/jd/*</url-pattern>
	</filter-mapping>
 	
	<servlet>
		<servlet-name>market</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>

	<servlet-mapping>
		<servlet-name>market</servlet-name>
		<url-pattern>/jd/*</url-pattern>
	</servlet-mapping>

</web-app>

market-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

	 <context:annotation-config />
	 <mvc:annotation-driven />  
	
	<context:component-scan base-package="cn.cloud.controller"></context:component-scan>

	<bean id="viewResolver"
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="viewClass"
			value="org.springframework.web.servlet.view.JstlView" />
		<property name="prefix" value="/page" />
		<property name="suffix" value="" />
	</bean>

</beans>

applicationContext-security.xml

<?xml version="1.0" encoding="UTF-8"?>
<b:beans xmlns="http://www.springframework.org/schema/security"
	xmlns:b="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.2.xsd
                        http://www.springframework.org/schema/security 
                        http://www.springframework.org/schema/security/spring-security-3.2.xsd">

	<http pattern="/jd/auth/*" security="none"></http>

	<http access-denied-page="/jd/auth/denied" use-expressions="true">

		<form-login login-page="/jd/auth/login" default-target-url="/jd/bbs/show"
			login-processing-url="/jd/j_spring_security_check"
			authentication-failure-url="/jd/auth/login?msg=error" />

		<custom-filter before="FILTER_SECURITY_INTERCEPTOR" ref="filterInvocationInterceptor" />
	</http>
	
	<b:bean id="cloudAccessDecisionManager" class="cn.cloud.service.auth.CloudAccessDecisionManager"></b:bean>
	<b:bean id="securityMetadataSource" class="cn.cloud.service.auth.CloudSecurityMetadataSource" />

	<b:bean id="filterInvocationInterceptor" class="cn.cloud.service.auth.CloudSecurityFilter">
		<b:property name="authenticationManager" ref="authenticationManager" />
		<b:property name="accessDecisionManager" ref="cloudAccessDecisionManager" />
		<b:property name="securityMetadataSource" ref="securityMetadataSource" />
	</b:bean>
	
	
	<b:bean id="cloudUserDetailsService" class="cn.cloud.service.auth.CloudUserDetailsService"></b:bean>

	<authentication-manager alias="authenticationManager">
		<authentication-provider user-service-ref="cloudUserDetailsService"></authentication-provider>
	</authentication-manager>
	
</b:beans>

DemoController.java

package cn.cloud.controller;

import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class DemoController 
{
	@RequestMapping(value="/auth/login")
	public String login(HttpServletRequest request)
	{
		return "/auth/login.jsp";
	}
	
	@RequestMapping(value="/auth/logout", produces="text/html;charset=UTF-8")
	@ResponseBody()
	public String logout()
	{
		return "<h1>this is auth.logout</h1>";
	}
	
	@RequestMapping(value="/auth/denied", produces="text/html;charset=UTF-8")
	@ResponseBody()
	public String denied()
	{
		return "<h1 style='color:red;'>no right</h1>";
	}
	
	@RequestMapping("/admin/list")
	@ResponseBody()
	public String index(HttpServletRequest request)
	{
		request.getSession().setAttribute("user", "admin");
		return "<h1>this is admin.list</h1>";
	}
	
	@RequestMapping("/admin/access")
	@ResponseBody()
	public String access(HttpServletRequest request)
	{
		String user = (String)request.getSession().getAttribute("user");
		return "<h1>this is admin.acccess<br />login user is "+user+"</h1>";
	}
	
	@RequestMapping("/hr/job")
	@ResponseBody()
	public String job()
	{
		return "<h1>this is hr.job</h1>";
	}
	
	@RequestMapping("/hr/employ")
	@ResponseBody()
	public String employ()
	{
		return "<h1>this is hr.employ</h1>";
	}
	
	@RequestMapping(value="/bbs/show", produces="text/html;charset=UTF-8")
	@ResponseBody()
	public String bbs(HttpServletRequest request)
	{
		return "<h1>this is bbs.show</h1>";
	}
	
	@RequestMapping(value="/blog/show", produces="text/html;charset=UTF-8")
	@ResponseBody()
	public String blog()
	{
		return "<h1>this is list.blog</h1>";
	}
}

CloudUserDetails.java

package cn.cloud.bean.auth;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

public class CloudUserDetails implements UserDetails 
{
	private static final long serialVersionUID = 1L;
	
	private String username;
	
	public CloudUserDetails(String username)
	{
		this.username = username;
	}
	public Collection<? extends GrantedAuthority> getAuthorities() 
	{
		return UserRole.getRoles(username);
	}
	public String getPassword()
	{
		return username;
	}
	public String getUsername()
	{
		return username;
	}
	public boolean isAccountNonExpired() 
	{
		return true;
	}
	public boolean isAccountNonLocked() 
	{
		return true;
	}
	public boolean isCredentialsNonExpired() 
	{
		return true;
	}
	public boolean isEnabled() 
	{
		return true;
	}
	public boolean equals(Object obj)
	{
		CloudUserDetails other = (CloudUserDetails)obj;
		
		return this.getUsername().equals(other.getUsername());
	}
}
class UserRole
{
	private static Map<String, Collection<SimpleGrantedAuthority>> map = new HashMap<>();
	
	static
	{
		map.put("user", new ArrayList<SimpleGrantedAuthority>());
		map.put("hr", new ArrayList<SimpleGrantedAuthority>());
		map.put("boss", new ArrayList<SimpleGrantedAuthority>());
		
		map.get("user").add(new SimpleGrantedAuthority("ROLE_USER"));
		
		map.get("hr").add(new SimpleGrantedAuthority("ROLE_HR"));
		map.get("hr").add(new SimpleGrantedAuthority("ROLE_USER"));
		
		map.get("boss").add(new SimpleGrantedAuthority("ROLE_USER"));
		map.get("boss").add(new SimpleGrantedAuthority("ROLE_HR"));
		map.get("boss").add(new SimpleGrantedAuthority("ROLE_BOSS"));
	}
	
	private UserRole(){}
	
	public static Collection<SimpleGrantedAuthority> getRoles(String username)
	{
		return map.get(username);
	}
}

CloudUserDetails.java

package cn.cloud.bean.auth;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

public class CloudUserDetails implements UserDetails 
{
	private static final long serialVersionUID = 1L;
	
	private String username;
	
	public CloudUserDetails(String username)
	{
		this.username = username;
	}
	public Collection<? extends GrantedAuthority> getAuthorities() 
	{
		return UserRole.getRoles(username);
	}
	public String getPassword()
	{
		return username;
	}
	public String getUsername()
	{
		return username;
	}
	public boolean isAccountNonExpired() 
	{
		return true;
	}
	public boolean isAccountNonLocked() 
	{
		return true;
	}
	public boolean isCredentialsNonExpired() 
	{
		return true;
	}
	public boolean isEnabled() 
	{
		return true;
	}
	public boolean equals(Object obj)
	{
		CloudUserDetails other = (CloudUserDetails)obj;
		
		return this.getUsername().equals(other.getUsername());
	}
}
class UserRole
{
	private static Map<String, Collection<SimpleGrantedAuthority>> map = new HashMap<>();
	
	static
	{
		map.put("user", new ArrayList<SimpleGrantedAuthority>());
		map.put("hr", new ArrayList<SimpleGrantedAuthority>());
		map.put("boss", new ArrayList<SimpleGrantedAuthority>());
		
		map.get("user").add(new SimpleGrantedAuthority("ROLE_USER"));
		
		map.get("hr").add(new SimpleGrantedAuthority("ROLE_HR"));
		map.get("hr").add(new SimpleGrantedAuthority("ROLE_USER"));
		
		map.get("boss").add(new SimpleGrantedAuthority("ROLE_USER"));
		map.get("boss").add(new SimpleGrantedAuthority("ROLE_HR"));
		map.get("boss").add(new SimpleGrantedAuthority("ROLE_BOSS"));
	}
	
	private UserRole(){}
	
	public static Collection<SimpleGrantedAuthority> getRoles(String username)
	{
		return map.get(username);
	}
}

CloudAccessDecisionManager.java

package cn.cloud.service.auth;

import java.util.Collection;

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;

public class CloudAccessDecisionManager implements AccessDecisionManager
{
	public void decide(Authentication authentication, Object object,Collection<ConfigAttribute> configAttributes)
	throws AccessDeniedException, InsufficientAuthenticationException
	{
		Collection<? extends GrantedAuthority> auths = authentication.getAuthorities();
		
		for(ConfigAttribute role : configAttributes)
		{
			for(GrantedAuthority sga : auths)
			{
				if(role.getAttribute().equals(sga.getAuthority()))
				{
					return;
				}
			}
		}
		
		throw new AccessDeniedException("Access Denied !");
	}
	public boolean supports(ConfigAttribute attribute)
	{
		return true;
	}
	public boolean supports(Class<?> clazz) 
	{
		return true;
	}
}

CloudSecurityFilter.java

package cn.cloud.service.auth;

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;

public class CloudSecurityFilter extends AbstractSecurityInterceptor implements Filter
{
	private SecurityMetadataSource securityMetadataSource;

	public void destroy() 
	{
		
	}
	public void doFilter(ServletRequest req, ServletResponse resp,FilterChain chain) throws IOException, ServletException 
	{
		FilterInvocation fi = new FilterInvocation(req, resp, chain);  
		
		InterceptorStatusToken token = super.beforeInvocation(fi);
		
		try
		{  
            fi.getChain().doFilter(fi.getRequest(), fi.getResponse());  
        } 
		finally
		{  
            super.afterInvocation(token, null);  
        }  
	}
	public void init(FilterConfig chain) throws ServletException 
	{
		
	}
	public Class<?> getSecureObjectClass() 
	{
		return FilterInvocation.class; 
	}
	public SecurityMetadataSource obtainSecurityMetadataSource()
	{
		return securityMetadataSource;
	}
	public SecurityMetadataSource getSecurityMetadataSource()
	{
		return securityMetadataSource;
	}
	public void setSecurityMetadataSource(SecurityMetadataSource securityMetadataSource)
	{
		this.securityMetadataSource = securityMetadataSource;
	}
}

CloudSecurityMetadataSource.java

package cn.cloud.service.auth;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityMetadataSource;
import org.springframework.security.web.FilterInvocation;

public class CloudSecurityMetadataSource implements SecurityMetadataSource
{
	public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException 
	{
		if(object != null)
		{
			FilterInvocation fi = (FilterInvocation)object;
			String url = fi.getRequestUrl();
			return UrlRole.getAttributes(url);
		}
		return null;
	}
	public Collection<ConfigAttribute> getAllConfigAttributes() 
	{
		return null;
	}
	public boolean supports(Class<?> clazz)
	{
		return true;
	}
}

class UrlRole
{	
	private static Map<String, Collection<ConfigAttribute>> map = new HashMap<>();
	
	static
	{
		map.put("/bbs/", new ArrayList<ConfigAttribute>());
		map.put("/blog/", new ArrayList<ConfigAttribute>());
		map.put("/hr/", new ArrayList<ConfigAttribute>());
		map.put("/admin/", new ArrayList<ConfigAttribute>());
		
		map.get("/bbs/").add(new Role("ROLE_USER"));
		map.get("/bbs/").add(new Role("ROLE_HR"));
		map.get("/bbs/").add(new Role("ROLE_BOSS"));
		
		map.get("/blog/").add(new Role("ROLE_USER"));
		map.get("/blog/").add(new Role("ROLE_HR"));
		map.get("/blog/").add(new Role("ROLE_BOSS"));
		
		map.get("/hr/").add(new Role("ROLE_HR"));
		map.get("/hr/").add(new Role("ROLE_BOSS"));
		
		map.get("/admin/").add(new Role("ROLE_BOSS"));
		
	}
	private UrlRole(){}
	private static String getRealUrl(String url)
	{
		String regex = "/\\w+\\/";
		url = url.replace("/jd", "");
		
		Pattern p = Pattern.compile(regex);
		
		Matcher ma = p.matcher(url);
		
		if(ma.find())
		{
			return ma.group();
		}
		
		return url;
	}
	
	public static Collection<ConfigAttribute> getAttributes(String url)
	{
		return map.get(getRealUrl(url));
	}
}

class Role implements ConfigAttribute
{
	private static final long serialVersionUID = 1L;
	private String role;
	public Role(String role)
	{
		this.role = role;
	}
	public String getAttribute() 
	{
		return role;
	}
	public String toString()
	{
		return "[role="+role+"]";
	}
}










CloudUserDetailsService.java

package cn.cloud.service.auth;

import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import cn.cloud.bean.auth.CloudUserDetails;

public class CloudUserDetailsService implements UserDetailsService
{
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException
	{
		return new CloudUserDetails(username);
	}
}


  • 7
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值