配置Spring Security 权限标签
博客专区 > _Artisan 的博客 > 博客详情
配置Spring Security 权限标签
_Artisan 发表于8个月前
配置Spring Security 权限标签
  • 发表于 8个月前
  • 阅读 25
  • 收藏 0
  • 点赞 0
  • 评论 0

新睿云服务器60天免费使用,快来体验!>>>   

在这里附上项目的地址,喜欢的可以给个star:https://git.oschina.net/huyup/shiyanshebeiguanlixinxixitong

1、Spring Security 所需的依赖

		<!-- spring-security -->
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-core</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-config</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-taglibs</artifactId>
			<version>${spring.version}</version>
		</dependency>

2、spring-security.xml 的配置

<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.xsd">

	<!-- 不拦截的资源 -->
	<http pattern="/static/**" security="none" />
	<http pattern="/login.jsp" security="none" />
	
	<http auto-config="true" use-expressions="false">
		<!-- 配置用户正常访问page-->
		<intercept-url pattern="/**" access="ROLE_USER"/>

		 <form-login login-page="/login.jsp"
					 username-parameter="user.userName"  
					 password-parameter="user.userPassword"
					 authentication-success-handler-ref="loginSuccessHandler"
					 authentication-failure-handler-ref="loginFailHandler"  /> 
	</http>
	
	
	<!--用户权限管理-->
    <authentication-manager alias="authenticationManager">
        <authentication-provider user-service-ref="userInfoProvider" >
        </authentication-provider>
    </authentication-manager>

    <!--用户信息Provider-->
    <beans:bean id="userInfoProvider" class="com.gxuwz.service.impl.UserInfoServiceImpl" />
    
    <!--登陆成功-->
    <beans:bean id="loginSuccessHandler" class="com.gxuwz.handler.MyLoginSuccessHandler" />
    
    <!--登陆失败-->
    <beans:bean id="loginFailHandler" class="com.gxuwz.handler.MyLoginFailHandler"/>  

</beans:beans>

3、用户实体代码(与角色是多对多的关系,在这就不贴角色实体的代码了)

package com.gxuwz.entity;

import java.util.*;
import javax.persistence.*;
import org.springframework.security.core.*;

/**
 * 用户实体
 * @author 小胡  
 * @date 2017年5月28日
 */
@Entity
@Table(name = "sys_user")
public class SysUser extends BaseEntity implements UserDetails{

	private static final long serialVersionUID = 103889943178214590L;

	@Column(name = "user_name", unique = true, nullable = false)
	private String userName; // 用户名
	@Column(name = "user_password")
	private String userPassword; // 密码
	@ManyToMany(fetch = FetchType.EAGER)
	@JoinTable(name = "sys_user_role", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id"))
	private Set<SysRole> user_role; // 所属角色
	@Column(name = "telephone")
	private String telephone; // 电话
	@Column(name = "user_create_date")
	private String createDate; // 创建日期
	@ManyToMany(fetch = FetchType.EAGER)
	@JoinTable(name = "sys_user_lab", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "lab_id"))
	private Set<SysLaboratory> user_lab;

	public SysUser() {

	}
        // 省略属性的get、set的方法
	
	@Override
	public Collection<? extends GrantedAuthority> getAuthorities() {
		Set<GrantedAuthority> auths = new HashSet<>();
        Set<SysRole> roles = this.getUser_role();
		// 默认所有的用户有"USER"的权利
        auths.add(new SimpleGrantedAuthority("ROLE_USER"));
        for (SysRole role : roles) {
            auths.add(new SimpleGrantedAuthority(role.getRoleName()));  //获得该用户所拥有的权限
        }
        return auths;
	}

	@Override
	public String getPassword() {
		return this.userPassword;
	}

	@Override
	public String getUsername() {
		return this.userName;
	}

	@Override
	public boolean isAccountNonExpired() {
		return true;
	}

	@Override
	public boolean isAccountNonLocked() {
		return true;
	}

	@Override
	public boolean isCredentialsNonExpired() {
		return true;
	}

	@Override
	public boolean isEnabled() {
		return true;
	}

}

4、用户信息的DAO

package com.gxuwz.dao;

import com.gxuwz.entity.SysUser;

public interface IUserInfoDao {
	public SysUser getUserByName(String username);
}

package com.gxuwz.dao.impl;

import javax.annotation.Resource;

import org.hibernate.*;
import org.springframework.*;

import com.gxuwz.dao.IUserInfoDao;
import com.gxuwz.entity.SysUser;

@Repository("userInfoDao")
public class UserInfoDaoImpl extends HibernateDaoSupport implements
		IUserInfoDao {

	@Resource(name = "sessionFactory")
	public void setSuperSessionFactory(SessionFactory sessionFactory) {
		super.setSessionFactory(sessionFactory);
	}

	@Override
	public SysUser getUserByName(String username) {
		Query query = this.getSession().createQuery(
				"from SysUser where user_name = ?");
		query.setString(0, username);
		SysUser user = (SysUser) query.uniqueResult();
		if (user == null) {
			return null;
		}else{
			return user;
		}
	}

}

5、用户信息的SERVICE

package com.gxuwz.service;

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

public interface IUserInfoService extends UserDetailsService{

}

package com.gxuwz.service.impl;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.gxuwz.dao.IUserInfoDao;
import com.gxuwz.entity.SysUser;
import com.gxuwz.service.IUserInfoService;

@Service("userInfoService")
public class UserInfoServiceImpl implements IUserInfoService {

	@Resource(name = "userInfoDao")
	private IUserInfoDao userInfoDao;

	@Override
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException {
		System.out.println("service login...");
		if (StringUtils.isNotEmpty(username)) {
			SysUser user = userInfoDao.getUserByName(username.trim());
			if (user != null) {
				System.out.println("用户名:"+user.getUsername()+" "+"密码:"+user.getPassword());
				return user;
			}
		}
		throw new UsernameNotFoundException(
				"Can't not find user while username is '" + username.trim()
						+ "'");
	}

}

6、struts2 的登陆的方法

	@LogMsg(msg="用户登陆")  // 这里使用Spring AOP的日志管理,具体看参考上一篇文章
	public String doLogin(){
		setPrompt("/WEB-INF/pages/main.jsp");	
		return SUCCESS;
	}

7、登陆页面的链接使用Spring Security自带的

    <ul>
    	<div style="padding:5px;text-align:center;color: red;">${msg}</div> 
    	<form name="loginForm" method="post" action="<%=basePath%>j_spring_security_check"> 
    	<li><input name="user.userName" type="text" class="loginuser" value="admin" onclick="JavaScript:this.value=''"/></li>
    	<li><input name="user.userPassword" type="password" class="loginpwd" value="密码" onclick="JavaScript:this.value=''"/></li>
    	<li><input name="" type="submit" class="loginbtn" value="登录" />
    	<label><input name="" type="checkbox" value="" checked="checked" />记住密码</label><label>
    	<a href="#">忘记密码?</a></label></li>
    	</form>
    </ul>

8、自定义的登陆成功和失败的处理

package com.gxuwz.handler;

import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.*;
import org.springframework.security.*;

import com.gxuwz.entity.SysUser;
import com.gxuwz.service.IUserInfoService;

/**
 * 配置登陆成功处理器
 * @author h
 *
 */
public class MyLoginSuccessHandler implements AuthenticationSuccessHandler {

	@Resource(name = "userInfoService")
	private IUserInfoService userInfoService;

	@Override
	public void onAuthenticationSuccess(HttpServletRequest req,
			HttpServletResponse resp, Authentication authentication)
			throws IOException, ServletException {
		SysUser user = null;
		Object o = SecurityContextHolder.getContext().getAuthentication()
				.getPrincipal();
		if (o != null && o instanceof SysUser) {
			user = (SysUser) o;
			resp.sendRedirect("User_doLogin.action");
			System.out.println("密码:" + user.getPassword());
			HttpSession session = req.getSession();
			if (session != null) {
				session.setAttribute("user", user);
			}
		}
	}

}

package com.gxuwz.handler;

import java.io.IOException;

import javax.servlet.*;
import org.springframework.security.*;

import com.gxuwz.common.Const;

/**
 * 配置登陆失败处理器
 * @author h
 *
 */
public class MyLoginFailHandler implements AuthenticationFailureHandler {

	@Override
	public void onAuthenticationFailure(HttpServletRequest req,
			HttpServletResponse resp,
			AuthenticationException authenticationexception)
			throws IOException, ServletException {
		resp.sendRedirect("login.jsp");
		HttpSession session = req.getSession();
		if (session != null) {
			session.setAttribute("msg", Const.LOGIN_ERROE_MSG);
		}
	}

}


9、具体的权限标签在WEB-INF/pages/left.jsp

    <!-- 权限标签 -->
    <!-- ifAllGranted,只有当前用户同时拥有 ROLE_ADMIN 和 ROLE_USER 两个权限时,才能显示标签内部内容 -->
    <!-- ifAnyGranted,如果当前用户拥有 ROLE_ADMIN 或 ROLE_USER 其中一个权限时,就能显示标签内部内容 --> 
    <!-- ifNotGranted,如果当前用户没有 ROLE_ADMIN 时,才能显示标签内部内容 -->
    <dd>
    <div class="title">
    <span><img src="static/images/leftico01.png" /></span>基本信息</div>
    	<ul class="menuson">
        <li  class="active"><cite></cite><a href="PageFrame_index.action" target="rightFrame">首页</a><i></i></li>
        <sec:authorize ifAnyGranted="ROLE_ADMIN">
        <li><cite></cite><a href="Department_listPrompt.action" target="rightFrame">部门列表</a><i></i></li>
        <li><cite></cite><a href="Laboratory_listPrompt.action" target="rightFrame">实验室列表</a><i></i></li>
        </sec:authorize>
        <sec:authorize ifAnyGranted="ROLE_ADMIN,ROLE_TCH,ROLE_TECH">
        <li><cite></cite><a href="Equipment_listPrompt.action" target="rightFrame">设备列表</a><i></i></li>
        </sec:authorize>
        <sec:authorize ifAnyGranted="ROLE_ADMIN">
        <li><cite></cite><a href="Role_listPrompt.action" target="rightFrame">角色列表</a><i></i></li>
        <li><cite></cite><a href="User_listPrompt.action" target="rightFrame">用户列表</a><i></i></li>
        </sec:authorize>
        </ul>    
    </dd>
  • 打赏
  • 点赞
  • 收藏
  • 分享
共有 人打赏支持
粉丝 2
博文 28
码字总数 9487
×
_Artisan
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: