首页 > 作文

Spring Security使用数据库登录认证授权

更新时间:2023-04-04 13:08:07 阅读: 评论:0

一、搭建项目环境

1、创建 rbac五张表

rbac,即基于角色的权限访问控制(role-bad access control),就是用户通过角色与权限进行关联。
在这种模型中,用户与角色之间,角色与权限之间,一般者是多对多的关系。

在 mysql数据库中,创建如下几个表:

drop table if exists sys_ur;create table sys_ur(    id bigint not null auto_increment  comment '主键id' ,    urname varchar(60)    comment '用户名' ,    password varchar(255)    comment '密码' ,    status tinyint(1)    comment '用户状态,1-开启-0禁用' ,    password_non_expired tinyint(1)    comment '密码是否失效,1-可用,0-失效' ,    primary key (id))  comment = '用户表';drop table if exists sys_role;create table sys_role(    id bigint not null auto_increment  comment '主键id' ,    role_name varchar(64) not null   comment '角色名' ,    role_desc varchar(64) not null   comment '角色描述' ,    primary key (id))  comment = '角色表';drop table if exists sys_permission;create table sys_permission(    id bigint not null auto_increment  comment '主键id' ,    parent_id bigint    comment '父id' ,    permission_name varchar(64)    comment '菜单名称' ,    permission_url varchar(255)    comment '菜单地址' ,    primary key (id))  comment = '权限表';drop table if exists sys_ur_role;create table sys_ur_role(    id bigint not null auto_increment  comment '主键id' ,    ur_id bigint not null   comment '用户id' ,    role_id bigint    comment '角色id' ,    enabled tinyint(1)   default 1 comment '是否有效' ,    primary key (id))  comment = '用户角色关联表';drop table if exists sys_role_permission;create table sys_role_permission(    id bigint not null auto_increment  comment '主键id' ,    role_id bigint not null   comment '角色id' ,    permission_id bigint    comment '权限id' ,    primary key (id))  comment = '角色权限表';

2、创建项目

创建 mavne 项目,springboot + spring curity + mybatis + mysql + jsp。

1)配置文件如下

rver:  port: 9090# jsp配置spring:  mvc:    view:      prefix: /pages/      suffix: .jsp  datasource:    driver-class-name: com.mysql.cj.jdbc.driver    url: jdbc:mysql://localhost:3306/curity_authority?uunicode=true;characterencoding=utf8;ussl=true;rvertimezone=gmt    urname: root    password: 123456# mybatis配置mybatis:  configuration:    map-underscore-to-camel-ca: true  mapper-locations: classpath:mybatis/mapper/*.xmllogging:  level:    com.charge.learn.springcurity.springboot.curity.jsp.dao: debug

2)启动类

@springbootapplication@mapperscan("com.charge.learn.springcurity.springboot.curity.jsp.dao")public class springcurityapplication {    public static void main(string[] args) {        springapplication.run(springcurityapplication.class, args);    }}

二、整合 spring curity实现用户认证

1、后端整合

1.1 用户

spring curity的用户对象是 urdetail类型,spring curity在认证流程中只认 urdetail用户。

通过 urdetailsrvice的 loadurbyurname方法获取 urdetail用户。认证成功之后,调用的是这个带有三个参数的 urnamepasswordauthenticationtoken构造方法,将 角色信息添加到了arraylist<grantedauthority>集合中。在 successfulauthentication 方法中,将认证信息存储到了curitycontext中。

urdetail接口的方法(根据用户业务来处理这几个值)。

boo杭州景色lean enabled 账户是否可用boolean accountnonexpired 账户是否失效boolean credentialsnonexpired 账户密码是否失效boolean accountnonlocked 账户是否锁定collection<? extends grantedau红色诗歌thority> getauthorities() 获取账户的所有权限(用户角色)

注意:四个布尔类型的参数都为 true时,然后成功,否则,有一个为 fal,就会认证失败。

所以,我们可以将我们的用户封装成 urdetail对象。
这里我们让用户对象实现 urdetail接口,那么我们用户就属于 urdetail类型的用户,然后实现接口的方法。

public class sysur implements urdetails {    private long id;    private string urname;    private string password;    private boolean status; //用户状态,1-开启-0禁用    private boolean passwordnonexpired; //密码是否失效,1-可用,0-失效    /**     * 用户关联的所有角色     */    private list<sysrole> roles = new arraylist<>();//get、t方法    //标记该字段不做json处理    @jsonignore    @override    public collection<? extends grantedauthority> getauthorities() {        return roles;    }    @jsonignore    @override    public boolean isaccountnonexpired() {        return true;    }    @jsonignore    @override    public boolean isaccountnonlocked() {        return true;    }    @jsonignore    @override    public boolean iscredentialsnonexpired() {        return passwordnonexpired == null ? fal : passwordnonexpired;    }    @jsonignore    @override    public boolean inabled() {        return status == null ? fal : status;    }}

1.2 角色

spring curity的权限对象是 grantedauthority类型。通过它的值来实现权限管理的。

所以,我们让角色对象实现grantedauthority接口,那么我们角色就属于 grantedauthority类型,然后实现接口的方法。
上面用户可以直接将 角色添加到 collection<? extends grantedauthority>集合中。

public class sysrole implements grantedauthority {    private long id;    private string rolename;    private string roledesc;//get、t方法    //标记该字段不做json处理    @jsonignore    @override    public string getauthority() {        return rolename;    }}

1.3 sysurrvice接受继承urdetailsrvice类

spring curity在认证流程中通过 urdetailsrvice的 loadurbyurname方法获取 urdetail用户。

所以,我们让 urrvice接口继承 urdetailsrvice类,然后重写 loadurbyurname方法。

在 loadurbyurname方法中,获取我们的用户信息( urdetail类型),记得将用户关联的角色也赋值为用户信息。

public interface s绵阳职业技术学校ysurrvice extends urdetailsrvice {    void save(sysur ur);}
@rvice@transactionalpublic class sysurrviceimpl implements sysur招行信用卡分期还款rvice {@autowiredprivate sysurmapper sysurmapper;@autowiredprivate sysrolemapper sysrolemapper;@autowiredprivate bcryptpasswordencoder passwordencoder;@overridepublic void save(sysur sysur) {// 将密码加密入库sysur.tpassword(passwordencoder.encode(sysur.getpassword()));sysurmapper.inrt(sysur);}/** * 认证业务 * * @param urname *            - 用户在浏览器输入的用户名 * @return urdetails - spring curity的用户对象,返回 null表示认证失败! * @throws urnamenotfoundexception */@overridepublic urdetails loadurbyurname(string urname) throws urnamenotfoundexception {/** * 用户信息和角色信息可以一步关联查询到位得到sysur,我这里分开查询 */// 1.查询用户sysur sysur = sysurmapper.getbyurname(urname);if (sysur == null) {return null;}// 2.获取用户关联的所有角色list<sysrole> sysroles = sysrolemapper.listallbyurid(sysur.getid());sysur.troles(sysroles);system.out.println("====> sysur=" + sysur.tostring());return sysur;}}

mapper.xml中的几个方法

  <lect id="getbyurname" resultmap="baresultmap">    lect id, urname, password, status, password_non_expired from sys_ur where urname = #{urname}  </lect>  <lect id="listallbyurid" resultmap="baresultmap">    lect r.id, r.role_name role_name, r.role_desc role_desc    from sys_role r, sys_ur_role ur    where r.id = ur.role_id and ur.ur_id = #{urid}  </lect>

1.4 创建 springcurity配置类

自定义一个配置类,添加@enablewebcurity注解,并继承webcurityconfigureradapter类。然后就拥有了 springcutiry的所有默认配置。我们也可以修改配置。

@configuration@enablewebcuritypublic class webcurityconfig extends webcurityconfigureradapter {    @autowired    private sysurrvice urrvice;    // 加密对象注入ioc容器    @bean    public bcryptpasswordencoder passwordencoder(){        return new bcryptpasswordencoder();    }    // 1.指定认证对象的来源(内存或者数据库),指定加密方式    @override    public void configure(authenticationmanagerbuilder auth) throws exception {        auth.urdetailsrvice(urrvice).passwordencoder(passwordencoder());    }    //2. springcurity配置相关信息    @override    public void configure(httpcurity http) throws exception {        // 释放静态资源,指定拦截规则,指定自定义的认证和退出页面,csrf配置等        http.authorizerequests()                // 指定拦截规则                .antmatchers("/login.jsp", "failer.jsp", "/css/**", "/img/**", "/plugins/**").permitall()  //释放这些资源,不拦截                .antmatchers("/**").hasanyrole("ur", "admin") //所有资源都需要这些角色中的一个                .anyrequest().authenticated()  //其他请求,必须认证通过之后才能访问                .and()  // 表示新的一个配置开始                // 指定自定义的认证页面                .formlogin()                .loginpage("/login.jsp")                .loginprocessingurl("/login")                .successforwardurl("/index.jsp")                .failureforwardurl("/failer.jsp")                .permitall() // 释放这些资源,不拦截登录                .and()                // 指定自定义的退出页面                .logout()                .logoutsuccessurl("/logout")                .invalidatehttpssion(true) // 清楚ssion                .logoutsuccessurl("/login.jsp")                .permitall()                //.and()//                禁用csrf配置,默认开启的(一般不写,页面要加csrf),这里我们测试下//                .and()//                .csrf()//                .disable()                ;    }

主要配置信息如下:

指定认证对象 sysurrvice (urdetailsrvice类型)指定了用户密码使用的加密对象springcurity配置相关信息,比如:指定拦截规则,指定自定义的认证页面,csrf等。

2、前端整合

在 spring curity 中,如果我们不做任何配置,默认的登录页面和登录接口的地址都是 /login,即默认会存在如下两个请求:

get http://localhost:8080/loginpost http://localhost:8080/login

如果是 get 请求表示你想访问登录页面,如果是 post 请求,表示你想提交登录数据。默认的表单字段为 urname和password。

springcurity 默认 是开启 csrf防护机制。
所以,在自定义的表单上添加上 _csrf隐藏input(必须要写在form表单里面)。

引入 curity标签库<%@taglib uri="http://www.springframework.org/curity/tags" prefix="curity"%><curity:csrfinput/>

启动项目,登录认证访问ok.

三、整合 spring curity实现用户授权

认证过程获取用户信息时,我们已经把用户关联的角色信息设置到了 urdetails中,所以,我们只需要分配 资源访问的角色就可以了。

1、后端

1.1 开启 spring curity权限控制

spring curity可以通过注解的方式来控制类或者方法的访问权限。支持开启权限控制的注解类型如下:

jsr250-annotations:表示支持 jsr250-api的注解pre-post-annotations:表示支持 spring表达式注解cured-annotations:这才是 spring curity提供的注解

在实际开发中,用一类即可,三个都开启也没关系。
在 springcurity配置类上 添加 @enableglobalmethodcurity注解,表示开启 spring curity权限控制,这里我们三类都开启了。

@configuration@enablewebcurity@enableglobalmethodcurity(curedenabled=true, prepostenabled = true, jsr250enabled = true)public class webcurityconfig extends webcurityconfigureradapter {    ...
@configuration@enablewebcurity@enableglobalmethodcurity(curedenabled=true, prepostenabled = true, jsr250enabled = true)public class webcurityconfig extends webcurityconfigureradapter {...

1.2 在角色对应类或者方法上添加权限注解

1.2.1 使用 spring curity注解

@cured({“role_admin”,“role_product”})
@controller@requestmapping("/ur")@cured("role_admin") //表示当前类中所有方法需要 role_admin才能访问public class urcontroller {    @autowired    private urrvice urrvice;    @requestmapping("/findall")    public string findall(model model){        list<sysur> list = urrvice.findall();        model.addattribute("list", list);        return "ur-list";    }    。。。 }

1.2.2 使用 spring表达式注解

@preauthorize(“hasanyrole(‘role_admin’,‘role_product’)”)
@controller@requestmapping("/product")public class productcontroller {        @requestmapping("/findall")    //表示当前类中findall方法需要 role_admin或者 role_product才能访问    @preauthorize("hasanyrole('role_admin','role_product')")     public string findall(){        return "product-list";    }}

1.2.3 使用 jsr-250注解

@rolesallowed({“role_admin”,“role_ur”})
@controller@requestmapping("/order")@rolesallowed({"role_admin","role_ur"}) //表示当前类中所有方法都需要role_admin或者role_ur才能访问public class ordercontroller {        @requestmapping("/findall")    public string findall(){        return "order-lis秋雨夜寒t";    }}

2、前端

在jsp业页面中,对每个菜单资源通过 springcurity标签库指定访问所需的角色。

<%@taglib uri="http://www.springframework.org/curity/tags" prefix="curity" %><!-- 指定访问所需角色 --><curity:authorize access="hasanyrole('role_admin', '等等')">

启动项目,通过不同的用户登录,授权访问ok.

到此这篇关于spring curity使用数据库登录认证授权的文章就介绍到这了,更多相关spring curity数据库登录认证授权内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.com!

本文发布于:2023-04-04 13:07:56,感谢您对本站的认可!

本文链接:https://www.wtabcd.cn/fanwen/zuowen/d1bca207d0f3fe44c2f148acbfd9b33c.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

本文word下载地址:Spring Security使用数据库登录认证授权.doc

本文 PDF 下载地址:Spring Security使用数据库登录认证授权.pdf

标签:角色   用户   注解   方法
相关文章
留言与评论(共有 0 条评论)
   
验证码:
Copyright ©2019-2022 Comsenz Inc.Powered by © 专利检索| 网站地图