当前位置: 移动技术网 > IT编程>数据库>MSSQL > Spring security实现登陆和权限角色控制

Spring security实现登陆和权限角色控制

2017年12月01日  | 移动技术网IT编程  | 我要评论
 随笔简介   1、spring版本:4.3.2.release+spring security 版本:4.1.2.release(其它不做说明)   2、所

 随笔简介

  1、spring版本:4.3.2.release+spring security 版本:4.1.2.release(其它不做说明)
  2、所展示内容全部用注解配置
  3、springmvc已经配置好,不作说明
  4、会涉及到springmvc,spel,el的东西,不熟悉的同学可以先去看一下这方面内容,特别是springmvc 

首先想一下,登陆需要什么,最简单的情况下,用户名,密码,然后比对数据库,如果吻合就跳转到个人页面,否则回到登陆页面,并且提示用户名密码错误。这个过程中应该还带有权限角色,并且贯穿整个会话。有了这个思路,我们只需要把数据库的用户名密码交给spring security比对,再让security进行相关跳转,并且让security帮我们把权限角色和用户名贯穿整个会话,实际上,我们只需要提供正确的用户名和密码,以及配置下security。  

目录

准备工作
登陆页面
个人页面
开始配置spring security

1.启动spring security

2.配置权限

3.编写userdetailservice 

首先准备数据库表

create table `user` (
 `username` varchar(255) not null,
 `password` char(255) not null,
 `roles` enum('member','member,leader','super_admin') not null default 'member',
 primary key (`username`),
 key `username` (`username`)
) engine=innodb default charset=utf8;

ps:这里注意的是roles的内容,leader也是member,这样做,leader就拥有member的权限,当然你也可以在应用里面作判断,这个后面会说到。

 登陆页面

<%@ page contenttype="text/html;charset=utf-8" language="java" iselignored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="sf" uri="http://www.springframework.org/tags/form"%>
<html>
<head>
 <title>登录</title>
</head>
<body>
<div >
 
 <sf:form action="${pagecontext.request.contextpath}/log" method="post" commandname="user">  <!-- spring表单标签,用于模型绑定和自动添加隐藏的csrf token标签 -->
  <h1 >登录</h1>
  <c:if test="${error==true}"><p style="color: red">错误的帐号或密码</p></c:if>      <!-- 登陆失败会显示这句话 -->
  <c:if test="${logout==true}"><p >已退出登录</p></c:if>                    <!-- 退出登陆会显示这句话 -->
  <sf:input path="username" name="user.username" placeholder="输入帐号" /><br />
  <sf:password path="password" name="user.password" placeholder="输入密码" /><br />
  <input id="remember-me" name="remember-me" type="checkbox"/>                <!-- 是否记住我功能勾选框 -->
  <label for="remember-me">一周内记住我</label>
  <input type="submit" class="sumbit" value="提交" >
 </sf:form>
</div>
</body>
</html> 

个人页面

<%@ page contenttype="text/html;charset=utf-8" language="java" iselignored="false"%>
<%@taglib prefix="security" uri="http://www.springframework.org/security/tags" %>
<%@ taglib prefix="sf" uri="http://www.springframework.org/tags/form"%>
<html>
<head>
 <title>欢迎你,<security:authentication property="principal.username" var="username"/>${username}</title>      <!-- 登陆成功会显示名字,这里var保存用户名字到username变量,下面就可以通过el获取 -->
</head>
<body>
<security:authorize access="isauthenticated()"><h3>登录成功!${username}</h3></security:authorize>  <!-- 登陆成功会显示名字 -->

<security:authorize access="hasrole('member')">              <!-- menber角色就会显示 security:authorize标签里的内容-->
 <p>你是menber</p>
</security:authorize>

<security:authorize access="hasrole('leader')">
 <p>你是leader</p>
</security:authorize>


<sf:form id="logoutform" action="${pagecontext.request.contextpath}/logout" method="post">      <!-- 登出按钮,注意这里是post,get是会登出失败的 -->
 <a href="#" onclick="document.getelementbyid('logoutform').submit();">注销</a>
</sf:form>
</body>
</html>

开始配置spring security

1.启动spring security      

@order(2)
public class websecurityappinit extends abstractsecuritywebapplicationinitializer{
}

  继承abstractsecuritywebapplicationinitializer,spring security会自动进行准备工作,这里@order(2)是之前我springmvc(也是纯注解配置)和spring security一起启动出错,具体是什么我忘了,加这个让security启动在后,可以避免这个问题,如果不写@order(2)没有错就不用管。

2.配置权限

@configuration
@enablewebsecurity
@componentscan("com.chuanzhi.workspace.service.impl.*")
public class websecurityconfig extends websecurityconfigureradapter{          

 @autowired
 private userdetailservice userdetailservice;  //如果userdetailservice没有扫描到就加上面的@componentscan

 @override
 protected void configure(httpsecurity http) throws exception {
  http.authorizerequests()
     .antmatchers("/me").hasanyrole("member","super_admin")//个人首页只允许拥有menber,super_admin角色的用户访问
     .anyrequest().authenticated()
     .and()
    .formlogin()
     .loginpage("/").permitall()        //这里程序默认路径就是登陆页面,允许所有人进行登陆
     .loginprocessingurl("/log")         //登陆提交的处理url
     .failureforwardurl("/?error=true")   //登陆失败进行转发,这里回到登陆页面,参数error可以告知登陆状态
     .defaultsuccessurl("/me")        //登陆成功的url,这里去到个人首页
     .and()
    .logout().logouturl("/logout").permitall().logoutsuccessurl("/?logout=true")    //按顺序,第一个是登出的url,security会拦截这个url进行处理,所以登出不需要我们实现,第二个是登出url,logout告知登陆状态
     .and()
    .rememberme()
     .tokenvalidityseconds(604800)     //记住我功能,cookies有限期是一周
     .remembermeparameter("remember-me")   //登陆时是否激活记住我功能的参数名字,在登陆页面有展示
     .remembermecookiename("workspace");   //cookies的名字,登陆后可以通过浏览器查看cookies名字
 }

 @override
 public void configure(websecurity web) throws exception {
  super.configure(web);
 }

 @override
 protected void configure(authenticationmanagerbuilder auth) throws exception {
  auth.userdetailsservice(userdetailservice);  //配置自定义userdetailservice
 }
}

3.编写userdetailservice

  spring security提供给我们的获取用户信息的service,主要给security提供验证用户的信息,这里我们就可以自定义自己的需求了,我这个就是根据username从数据库获取该用户的信息,然后交给security进行后续处理

@service(value = "userdetailservice")
public class userdetailservice implements userdetailsservice {

 @autowired
 private userrepository repository;          

 public userdetailservice(userrepository userrepository){
  this.repository = userrepository;              //用户仓库,这里不作说明了
 }

 public userdetails loaduserbyusername(string username) throws usernamenotfoundexception {

  user user = repository.finduserbyusername(username);
  if (user==null)
   throw new usernamenotfoundexception("找不到该账户信息!");          //抛出异常,会根据配置跳到登录失败页面

  list<grantedauthority> list = new arraylist<grantedauthority>();      //grantedauthority是security提供的权限类,

  getroles(user,list);              //获取角色,放到list里面

  org.springframework.security.core.userdetails.user auth_user = new
    org.springframework.security.core.userdetails.user(user.getusername(),user.getpassword(),list);      //返回包括权限角色的user给security
  return auth_user;
 }

 /**
  * 获取所属角色
  * @param user
  * @param list
  */
 public void getroles(user user,list<grantedauthority> list){
  for (string role:user.getroles().split(",")) {
   list.add(new simplegrantedauthority("role_"+role));          //权限如果前缀是role_,security就会认为这是个角色信息,而不是权限,例如role_menber就是menber角色,can_send就是can_send权限
  }
 }
}

如果你想在记住我功能有效情况下,在下次进入登陆页面直接跳到个人首页可以看一下这个控制器代码

/**
  * 登录页面
  * @param
  * @return
  */
 @requestmapping(value = "/")
 public string login(model model,user user
   ,@requestparam(value = "error",required = false) boolean error
   ,@requestparam(value = "logout",required = false) boolean logout,httpservletrequest request){
  model.addattribute(user);
  //如果已经登陆跳转到个人首页
  authentication authentication = securitycontextholder.getcontext().getauthentication();
  if(authentication!=null&&
    !authentication.getprincipal().equals("anonymoususer")&&
    authentication.isauthenticated())
   return "me";
  if(error==true)
   model.addattribute("error",error);
  if(logout==true)
   model.addattribute("logout",logout);
  return "login";
 } 

结果展示:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网