侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

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

技术  /  管理员 发布于 7年前   177

 随笔简介

  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"; } 

结果展示:

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


  • 上一条:
    用jdom创建中文的xml文件的方法
    下一条:
    一个删除指定表的所有索引和统计的过程
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 智能合约Solidity学习CryptoZombie第三课:组建僵尸军队(高级Solidity理论)(0个评论)
    • 智能合约Solidity学习CryptoZombie第二课:让你的僵尸猎食(0个评论)
    • 智能合约Solidity学习CryptoZombie第一课:生成一只你的僵尸(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 2024.07.09日OpenAI将终止对中国等国家和地区API服务(0个评论)
    • 近期文章
    • 智能合约Solidity学习CryptoZombie第三课:组建僵尸军队(高级Solidity理论)(0个评论)
    • 智能合约Solidity学习CryptoZombie第二课:让你的僵尸猎食(0个评论)
    • 智能合约Solidity学习CryptoZombie第一课:生成一只你的僵尸(0个评论)
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2017-07
    • 2017-08
    • 2017-09
    • 2018-01
    • 2018-07
    • 2018-08
    • 2018-09
    • 2018-12
    • 2019-01
    • 2019-02
    • 2019-03
    • 2019-04
    • 2019-05
    • 2019-06
    • 2019-07
    • 2019-08
    • 2019-09
    • 2019-10
    • 2019-11
    • 2019-12
    • 2020-01
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2020-07
    • 2020-08
    • 2020-09
    • 2020-10
    • 2020-11
    • 2021-04
    • 2021-05
    • 2021-06
    • 2021-07
    • 2021-08
    • 2021-09
    • 2021-10
    • 2021-12
    • 2022-01
    • 2022-02
    • 2022-03
    • 2022-04
    • 2022-05
    • 2022-06
    • 2022-07
    • 2022-08
    • 2022-09
    • 2022-10
    • 2022-11
    • 2022-12
    • 2023-01
    • 2023-02
    • 2023-03
    • 2023-04
    • 2023-05
    • 2023-06
    • 2023-07
    • 2023-08
    • 2023-09
    • 2023-10
    • 2023-12
    • 2024-02
    • 2024-04
    • 2024-05
    • 2024-06
    • 2025-02
    • 2025-07
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客