广告
返回顶部
首页 > 资讯 > 后端开发 > Python >SpringBoot集成Spring security JWT实现接口权限认证
  • 557
分享到

SpringBoot集成Spring security JWT实现接口权限认证

2024-04-02 19:04:59 557人浏览 泡泡鱼

Python 官方文档:入门教程 => 点击学习

摘要

1、添加依赖 <dependency> <groupId>org.springframework.boot</groupId>

1、添加依赖


<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

<dependency>
    <groupId>io.JSONWEBtoken</groupId>
    <artifactId>jJwt</artifactId>
    <version>0.9.1</version>
</dependency>

2、集成JWT工具类(JwtUtils)


package com.dreamteam.chdapp.utils;

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlGorithm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.Http.httpservletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


public class JwtUtils {
    private static final Logger logger= LoggerFactory.getLogger(JwtUtils.class);
    public static  final long EXPIRATION_TIME=60*60*1000;// 令牌环有效期
    public static final String SECRET="abc123456def";//令牌环密钥
    public static final String TOKEN_PREFIX="Bearer";//令牌环头标识
    public static final String HEADER_STRING="Passport";//配置令牌环在http heads中的键值
    public static final String ROLE="ROLE";//自定义字段-角色字段

    //生成令牌环
    public static String generateToken(String userRole,String userid){
        HashMap<String,Object> map=new HashMap<>();
        map.put(ROLE,userRole);
        map.put("userid",userid);
        String jwt= Jwts.builder()
                .setClaims(map)
                .setExpiration(new Date(System.currentTimeMillis()+EXPIRATION_TIME))
                .signWith(SignatureAlgorithm.HS512,SECRET)
                .compact();
        return TOKEN_PREFIX+" "+jwt;
    }
    //生成令牌环
    public static String generateToken(String userRole,String userid,long exprationtime){
        HashMap<String,Object> map=new HashMap<>();
        map.put(ROLE,userRole);
        map.put("userid",userid);
        String jwt= Jwts.builder()
                .setClaims(map)
                .setExpiration(new Date(System.currentTimeMillis()+exprationtime))
                .signWith(SignatureAlgorithm.HS512,SECRET)
                .compact();
        return TOKEN_PREFIX+" "+jwt;
    }

    //令牌环校验
    public static Map<String,Object> validateTokenAndGetClaims(HttpServletRequest request){
        String token=request.getHeader(HEADER_STRING);
        if(token==null){
            throw new TokenValidationException("Missing Token");

        }
        else{
            Map<String,Object> body= Jwts.parser()
                    .setSigningKey(SECRET)
                    .parseClaimsJws(token.replace(TOKEN_PREFIX,""))
                    .getBody();
            return body;
        }
    }
    
    static class TokenValidationException extends RuntimeException{
        public TokenValidationException(String msg){
            super(msg);
        }
    }
}

3、集成JWT filter(拦截器/过滤器)


package com.dreamteam.chdapp.filter;

import com.dreamteam.chdapp.utils.JwtUtils;
import org.springframework.security.authentication.UsernamePassWordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.Map;

import static com.dreamteam.chdapp.utils.JwtUtils.ROLE;


public class JwtAuthenticationFilter extends OncePerRequestFilter {
    private static final PathMatcher pathmatcher = new AntPathMatcher();
    private String[] protectUrlPattern = {"/manage
@Controller
public class CommonController {

    protected static final Logger log= LoggerFactory.getLogger(CommonController.class);

    
    public static boolean isNullOrSpace(String value){

        if(value==null){
            return true;
        }
        else {
            if(value.equals("")){
                return true;
            }
            else {
                return false;
            }
        }
    }
}

Service层


String getCurrentUserId();//从令牌环中获取userid
String getCurrentRole();//从令牌环中获取角色id

ServiceImpl



    @Override
    public String getCurrentUserId() {
        String userid= (String) SecurityContextHolder.getContext().getAuthentication() .getPrincipal();
        if(CommonController.isNullOrSpace(userid)){
            return null;
        }
        else {
            return userid;
        }
    }

    
    @Override
    public String getCurrentRole() {
        String role=null;
        Collection<SimpleGrantedAuthority> authorities = (Collection<SimpleGrantedAuthority>)    SecurityContextHolder.getContext().getAuthentication().getAuthorities();
        for (GrantedAuthority authority : authorities) {
            role = authority.getAuthority();

        }

        if(CommonController.isNullOrSpace(role)){
            return null;
        }
        else{
            return role;
        }
    }

修改manage的Controller类


    @GetMapping("testSecurityResource")
    @ResponseBody
    public String testSecurityResource() throws Exception{

        String userid=userInfoService.getCurrentUserId();
        String role=userInfoService.getCurrentRole();

        return "受保护的资源,当前用户的id是"+userid+"当前用户的角色是"+role;

    }

用postman测试

在这里插入图片描述

这是前面自定义的

在这里插入图片描述

8、识别token信息

在这里插入图片描述

如果将下图中的角色换掉,将不能访问

在这里插入图片描述

9、自动更新令牌环

添加Controller类


package com.dreamteam.chdapp.controller;

import com.dreamteam.chdapp.controller.common.CommonController;
import com.dreamteam.chdapp.utils.JwtUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
import java.util.HashMap;


@CrossOrigin
@RestController
@PreAuthorize("hasAnyAuthority('admin','member')")
@RequestMapping("/auth")
public class AuthController {
    
    @GetMapping("refreshToken")
    @ResponseBody
    public HashMap<String,String> refreshToken(HttpServletRequest request){


        String role=null;
        Collection<SimpleGrantedAuthority> authorities = (Collection<SimpleGrantedAuthority>)    SecurityContextHolder.getContext().getAuthentication().getAuthorities();
        for (GrantedAuthority authority : authorities) {
            role = authority.getAuthority();

        }
        // UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication() .getPrincipal();
        String userid= (String)SecurityContextHolder.getContext().getAuthentication() .getPrincipal();
        if(CommonController.isNullOrSpace(role)){
            return new HashMap<String,String>(){{
                put("token","error");
            }};
        }
        else{

            String jwt="";
            //一小时
            jwt= JwtUtils.generateToken(role,userid,60*60*1000);
            HashMap<String,String> m=new HashMap<>();
            m.put("token",jwt);
            return m;


        }

    }

    
    @GetMapping("getRole")
    @ResponseBody
    public HashMap<String,String> getRoleByToken(){

        String role="";
        String userid="";
        Collection<SimpleGrantedAuthority> authorities = (Collection<SimpleGrantedAuthority>)    SecurityContextHolder.getContext().getAuthentication().getAuthorities();
        for (GrantedAuthority authority : authorities) {
            role = authority.getAuthority();

        }
        if(CommonController.isNullOrSpace(role)){
            return new HashMap<String,String>(){{
                put("role","error");
            }};
        }
        else{

            HashMap<String,String> m=new HashMap<>();
            m.put("role",role);
            return m;
        }
    }
}

用postman测试

在这里插入图片描述

10、使用数据库存储用户信息

(1)实体类


package com.dreamteam.chdapp.entity;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.stereotype.Component;

@Component
@Data
@AllArgsConstructor
@NoArgsConstructor



@TableName("users")
public class Users {

    @TableId(type = IdType.AUTO)
    private String usrId;
    private String usrName;

    private String usrTel;

    private String usrPwd;

    private String usrType;
    
}

UserMapper


package com.dreamteam.chdapp.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.dreamteam.chdapp.entity.Users;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;

import java.util.List;


@Repository
@Mapper
public interface UserMapper extends BaseMapper<Users> {

    List<Users> getUsersByUsrNameAndPwd(@Param("usrName")String usrName, @Param("usrPwd") String usrPwd);
}

UsersMapper.xml


<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.dreamteam.chdapp.mapper.UserMapper">

    <select id="getUsersByUsrNameAndPwd" resultType="com.dreamteam.chdapp.entity.Users">
        select * from users where #{usrName}=usr_name and #{usrPwd}=usr_pwd
    </select>
</mapper>

service


Users getUsersByUsrNameAndPwd(String usrName,String usrPwd);

serviceImpl JWT获取用户名密码


    @Override
    public Users getUsersByUsrNameAndPwd(String usrName, String usrPwd) {
        List<Users> ul=userMapper.getUsersByUsrNameAndPwd(usrName,usrPwd);
        if(ul.size()>0){
            return ul.get(0);
        }
        return null;
    }

Controller


    @PostMapping("/login")
    @ResponseBody
    public HashMap<String,String> login(
            @RequestBody Account account) throws IOException {
        Users u=userInfoService.getUsersByUsrNameAndPwd(account.username,account.password);
//        if(account.username.equals("admin")&&account.password.equals("123456")){
        if(u!=null){
//            String jwt= JwtUtils.generateToken("admin","123456789abc");
            String jwt= JwtUtils.generateToken(u.getUsrType(),u.getUsrId());


            return new HashMap<String,String>(){{
                put("msg","ok");
                put("token",jwt);
                put("role",u.getUsrType());
//                put("role","admin");
            }};
        }
        else {
            //return new ResponseEntity(HttpStatus.UNAUTHORIZED);
            return new HashMap<String,String>(){{
                put("msg","error");
                put("token","error");
            }};
        }
    }

    public static class Account{
        public String username;
        public String password;
    }

postman测试

a.登录,生成token

在这里插入图片描述

b.输入token访问manage下的链接

在这里插入图片描述

到此这篇关于SpringBoot集成Spring security JWT实现接口权限认证的文章就介绍到这了,更多相关SpringBoot 接口权限认证内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: SpringBoot集成Spring security JWT实现接口权限认证

本文链接: https://www.lsjlt.com/news/123532.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作