欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

实战篇:Security+JWT组合拳 | 附源码

程序员文章站 2022-07-01 23:38:39
Good morning, everyone! 之前我们已经说过用Shiro和JWT来实现身份认证和用户授权,今天我们再来说一下Security和JWT的组合拳。 简介 先赘述一下身份认证和用户授权: 用户认证(Authentication):系统通过校验用户提供的用户名和密码来验证该用户是否为系统 ......

good morning, everyone!

之前我们已经说过用shiro和jwt来实现身份认证和用户授权,今天我们再来说一下security和jwt的组合拳。

简介

先赘述一下身份认证和用户授权:

  • 用户认证(authentication):系统通过校验用户提供的用户名和密码来验证该用户是否为系统中的合法主体,即是否可以访问该系统;
  • 用户授权(authorization):系统为用户分配不同的角色,以获取对应的权限,即验证该用户是否有权限执行该操作;

web应用的安全性包括用户认证和用户授权两个部分,而spring security(以下简称security)基于spring框架,正好可以完整解决该问题。

它的真正强大之处在于它可以轻松扩展以满足自定义要求。

原理

security可以看做是由一组filter过滤器链组成的权限认证。它的整个工作流程如下所示:
实战篇:Security+JWT组合拳 | 附源码
图中绿色认证方式是可以配置的,橘黄色和蓝色的位置不可更改:

  • filtersecurityinterceptor:最后的过滤器,它会决定当前的请求可不可以访问controller
  • exceptiontranslationfilter:异常过滤器,接收到异常消息时会引导用户进行认证;

实战

项目准备

我们使用spring boot框架来集成。

1.pom文件引入的依赖

<dependency>
    <groupid>org.springframework.boot</groupid>
    <artifactid>spring-boot-starter</artifactid>
</dependency>

<dependency>
    <groupid>org.springframework.boot</groupid>
    <artifactid>spring-boot-starter-web</artifactid>
    <exclusions>
        <exclusion>
            <groupid>org.springframework.boot</groupid>
            <artifactid>spring-boot-starter-tomcat</artifactid>
        </exclusion>
    </exclusions>
</dependency>

<dependency>
    <groupid>org.springframework.boot</groupid>
    <artifactid>spring-boot-starter-undertow</artifactid>
</dependency>

<dependency>
    <groupid>mysql</groupid>
    <artifactid>mysql-connector-java</artifactid>
</dependency>

<dependency>
    <groupid>com.baomidou</groupid>
    <artifactid>mybatis-plus-boot-starter</artifactid>
    <version>3.4.0</version>
</dependency>

<dependency>
    <groupid>org.projectlombok</groupid>
    <artifactid>lombok</artifactid>
</dependency>

<!-- 阿里json解析器 -->
<dependency>
    <groupid>com.alibaba</groupid>
    <artifactid>fastjson</artifactid>
    <version>1.2.74</version>
</dependency>

<dependency>
    <groupid>joda-time</groupid>
    <artifactid>joda-time</artifactid>
    <version>2.10.6</version>
</dependency>

<dependency>
    <groupid>org.springframework.boot</groupid>
    <artifactid>spring-boot-starter-test</artifactid>
</dependency>

2.application.yml配置

spring:
  application:
    name: securityjwt
  datasource:
    driver-class-name: com.mysql.cj.jdbc.driver
    url: jdbc:mysql://127.0.0.1:3306/cheetah?characterencoding=utf-8&usessl=false&servertimezone=utc
    username: root
    password: 123456

server:
  port: 8080

mybatis:
  mapper-locations: classpath:mapper/*.xml
  type-aliases-package: com.itcheetah.securityjwt.entity
  configuration:
    map-underscore-to-camel-case: true

rsa:
  key:
    pubkeyfile: c:\users\desktop\jwt\id_key_rsa.pub
    prikeyfile: c:\users\desktop\jwt\id_key_rsa

3.sql文件

/**
* sys_user_info
**/

set names utf8mb4;
set foreign_key_checks = 0;

-- ----------------------------
-- table structure for sys_user_info
-- ----------------------------
drop table if exists `sys_user_info`;
create table `sys_user_info`  (
  `id` bigint(20) not null auto_increment,
  `username` varchar(255) character set utf8 collate utf8_general_ci null default null,
  `password` varchar(255) character set utf8 collate utf8_general_ci null default null,
  primary key (`id`) using btree
) engine = innodb auto_increment = 3 character set = utf8 collate = utf8_general_ci row_format = dynamic;

set foreign_key_checks = 1;


/**
* product_info
**/

set names utf8mb4;
set foreign_key_checks = 0;

-- ----------------------------
-- table structure for product_info
-- ----------------------------
drop table if exists `product_info`;
create table `product_info`  (
  `id` bigint(20) not null auto_increment,
  `name` varchar(255) character set utf8 collate utf8_general_ci null default null,
  `price` decimal(10, 4) null default null,
  `create_date` datetime(0) null default null,
  `update_date` datetime(0) null default null,
  primary key (`id`) using btree
) engine = innodb auto_increment = 4 character set = utf8 collate = utf8_general_ci row_format = dynamic;

set foreign_key_checks = 1;

引入依赖

<dependency>
    <groupid>org.springframework.boot</groupid>
    <artifactid>spring-boot-starter-security</artifactid>
</dependency>

<!--token生成与解析-->
<dependency>
    <groupid>io.jsonwebtoken</groupid>
    <artifactid>jjwt</artifactid>
    <version>0.9.1</version>
</dependency>

引入之后启动项目,会有如图所示:
实战篇:Security+JWT组合拳 | 附源码
其中用户名为user,密码为上图中的字符串。

securityconfig类

//开启全局方法安全性
@enableglobalmethodsecurity(prepostenabled=true, securedenabled=true)
public class securityconfig extends websecurityconfigureradapter {

    //认证失败处理类
    @autowired
    private authenticationentrypointimpl unauthorizedhandler;

    //提供公钥私钥的配置类
    @autowired
    private rsakeyproperties prop;

    @autowired
    private userinfoservice userinfoservice;
    
    @override
    protected void configure(httpsecurity httpsecurity) throws exception {
        httpsecurity
                // csrf禁用,因为不使用session
                .csrf().disable()
                // 认证失败处理类
                .exceptionhandling().authenticationentrypoint(unauthorizedhandler).and()
                // 基于token,所以不需要session
                .sessionmanagement().sessioncreationpolicy(sessioncreationpolicy.stateless).and()
                // 过滤请求
                .authorizerequests()
                .antmatchers(
                        httpmethod.get,
                        "/*.html",
                        "/**/*.html",
                        "/**/*.css",
                        "/**/*.js"
                ).permitall()
                // 除上面外的所有请求全部需要鉴权认证
                .anyrequest().authenticated()
                .and()
                .headers().frameoptions().disable();
        // 添加jwt filter
        httpsecurity.addfilter(new tokenloginfilter(super.authenticationmanager(), prop))
                .addfilter(new tokenverifyfilter(super.authenticationmanager(), prop));
    }

    //指定认证对象的来源
    public void configure(authenticationmanagerbuilder auth) throws exception {
        
        auth.userdetailsservice(userinfoservice)
        //从前端传递过来的密码就会被加密,所以从数据库
        //查询到的密码必须是经过加密的,而这个过程都是
        //在用户注册的时候进行加密的。
        .passwordencoder(passwordencoder());
    }

    //密码加密
    @bean
    public bcryptpasswordencoder passwordencoder(){
        return new bcryptpasswordencoder();
    }
}

拦截规则

  • anyrequest:匹配所有请求路径
  • accessspringel表达式结果为true时可以访问
  • anonymous:匿名可以访问
  • `denyall:用户不能访问
  • fullyauthenticated:用户完全认证可以访问(非remember-me下自动登录)
  • hasanyauthority:如果有参数,参数表示权限,则其中任何一个权限可以访问
  • hasanyrole:如果有参数,参数表示角色,则其中任何一个角色可以访问
  • hasauthority:如果有参数,参数表示权限,则其权限可以访问
  • hasipaddress:如果有参数,参数表示ip地址,如果用户ip和参数匹配,则可以访问
  • hasrole:如果有参数,参数表示角色,则其角色可以访问
  • permitall:用户可以任意访问
  • rememberme:允许通过remember-me登录的用户访问
  • authenticated:用户登录后可访问

认证失败处理类

/**
 *  返回未授权
 */
@component
public class authenticationentrypointimpl implements authenticationentrypoint, serializable {

    private static final long serialversionuid = -8970718410437077606l;

    @override
    public void commence(httpservletrequest request, httpservletresponse response, authenticationexception e)
            throws ioexception {
        int code = httpstatus.unauthorized;
        string msg = "认证失败,无法访问系统资源,请先登陆";
        servletutils.renderstring(response, json.tojsonstring(ajaxresult.error(code, msg)));
    }
}

认证流程

自定义认证过滤器

public class tokenloginfilter extends usernamepasswordauthenticationfilter {

    private authenticationmanager authenticationmanager;

    private rsakeyproperties prop;

    public tokenloginfilter(authenticationmanager authenticationmanager, rsakeyproperties prop) {
        this.authenticationmanager = authenticationmanager;
        this.prop = prop;
    }

    /**
     * @author cheetah
     * @description 登陆验证
     * @date 2021/6/28 16:17
     * @param [request, response]
     * @return org.springframework.security.core.authentication
     **/
    public authentication attemptauthentication(httpservletrequest request, httpservletresponse response) throws authenticationexception {
        try {
            userpojo sysuser = new objectmapper().readvalue(request.getinputstream(), userpojo.class);
            usernamepasswordauthenticationtoken authrequest = new usernamepasswordauthenticationtoken(sysuser.getusername(), sysuser.getpassword());
            return authenticationmanager.authenticate(authrequest);
        }catch (exception e){
            try {
                response.setcontenttype("application/json;charset=utf-8");
                response.setstatus(httpservletresponse.sc_unauthorized);
                printwriter out = response.getwriter();
                map resultmap = new hashmap();
                resultmap.put("code", httpservletresponse.sc_unauthorized);
                resultmap.put("msg", "用户名或密码错误!");
                out.write(new objectmapper().writevalueasstring(resultmap));
                out.flush();
                out.close();
            }catch (exception outex){
                outex.printstacktrace();
            }
            throw new runtimeexception(e);
        }
    }


    /**
     * @author cheetah
     * @description 登陆成功回调
     * @date 2021/6/28 16:17
     * @param [request, response, chain, authresult]
     * @return void
     **/
    public void successfulauthentication(httpservletrequest request, httpservletresponse response, filterchain chain, authentication authresult) throws ioexception, servletexception {
        userpojo user = new userpojo();
        user.setusername(authresult.getname());
        user.setroles((list<rolepojo>)authresult.getauthorities());
        //通过私钥进行加密:token有效期一天
        string token = jwtutils.generatetokenexpireinminutes(user, prop.getprivatekey(), 24 * 60);
        response.addheader("authorization", "bearer "+token);
        try {
            response.setcontenttype("application/json;charset=utf-8");
            response.setstatus(httpservletresponse.sc_ok);
            printwriter out = response.getwriter();
            map resultmap = new hashmap();
            resultmap.put("code", httpservletresponse.sc_ok);
            resultmap.put("msg", "认证通过!");
            resultmap.put("token", token);
            out.write(new objectmapper().writevalueasstring(resultmap));
            out.flush();
            out.close();
        }catch (exception outex){
            outex.printstacktrace();
        }
    }
}

流程

security默认登录路径为/login,当我们调用该接口时,它会调用上边的attemptauthentication方法;
实战篇:Security+JWT组合拳 | 附源码
实战篇:Security+JWT组合拳 | 附源码
实战篇:Security+JWT组合拳 | 附源码
实战篇:Security+JWT组合拳 | 附源码
所以我们要自定义userinfoservice继承userdetailsservice实现loaduserbyusername方法;

public interface userinfoservice extends userdetailsservice {

}

@service
@transactional
public class userinfoserviceimpl implements userinfoservice {

    @autowired
    private sysuserinfomapper userinfomapper;

    @override
    public userdetails loaduserbyusername(string username) throws usernamenotfoundexception {
        userpojo user = userinfomapper.querybyusername(username);
        return user;
    }
}

其中的loaduserbyusername返回的是userdetails类型,所以userpojo继承userdetails

@data
public class userpojo implements userdetails {

    private integer id;

    private string username;

    private string password;

    private integer status;

    private list<rolepojo> roles;

    @jsonignore
    @override
    public collection<!--? extends grantedauthority--> getauthorities() {
        //理想型返回 admin 权限,可自已处理这块
        list<simplegrantedauthority> auth = new arraylist<>();
        auth.add(new simplegrantedauthority("admin"));
        return auth;
    }

    @override
    public string getpassword() {
        return this.password;
    }

    @override
    public string getusername() {
        return this.username;
    }

    /**
     * 账户是否过期
     **/
    @jsonignore
    @override
    public boolean isaccountnonexpired() {
        return true;
    }

    /**
     * 是否禁用
     */
    @jsonignore
    @override
    public boolean isaccountnonlocked() {
        return true;
    }

    /**
     * 密码是否过期
     */
    @jsonignore
    @override
    public boolean iscredentialsnonexpired() {
        return true;
    }

    /**
     * 是否启用
     */
    @jsonignore
    @override
    public boolean isenabled() {
        return true;
    }
}

当认证通过之后会在securitycontext中设置authentication对象,回调调用successfulauthentication方法返回token信息,
实战篇:Security+JWT组合拳 | 附源码

整体流程图如下

实战篇:Security+JWT组合拳 | 附源码

鉴权流程

自定义token过滤器

public class tokenverifyfilter extends basicauthenticationfilter {
    private rsakeyproperties prop;

    public tokenverifyfilter(authenticationmanager authenticationmanager, rsakeyproperties prop) {
        super(authenticationmanager);
        this.prop = prop;
    }

    public void dofilterinternal(httpservletrequest request, httpservletresponse response, filterchain chain) throws ioexception, servletexception {
        string header = request.getheader("authorization");
        if (header == null || !header.startswith("bearer ")) {
            //如果携带错误的token,则给用户提示请登录!
            chain.dofilter(request, response);
        } else {
            //如果携带了正确格式的token要先得到token
            string token = header.replace("bearer ", "");
            //通过公钥进行解密:验证tken是否正确
            payload<userpojo> payload = jwtutils.getinfofromtoken(token, prop.getpublickey(), userpojo.class);
            userpojo user = payload.getuserinfo();
            if(user!=null){
                usernamepasswordauthenticationtoken authresult = new usernamepasswordauthenticationtoken(user.getusername(), null, user.getauthorities());
                //将认证信息存到安全上下文中
                securitycontextholder.getcontext().setauthentication(authresult);
                chain.dofilter(request, response);
            }
        }
    }
}

当我们访问时需要在header中携带token信息
实战篇:Security+JWT组合拳 | 附源码

至于关于文中jwt生成tokenrsa生成公钥、私钥的部分,可在源码中查看,回复“sjwt”可获取完整源码呦!

以上就是今天的全部内容了,如果你有不同的意见或者更好的idea,欢迎联系阿q,添加阿q可以加入技术交流群参与讨论呦!

后台留言领取 java 干货资料:学习笔记与大厂面试题