首页 > 数据库 >从数据库查询权限信息与自定义失败处理

从数据库查询权限信息与自定义失败处理

时间:2023-04-26 11:33:42浏览次数:35  
标签:自定义 qinghuatokendemo 数据库 springframework org import security 权限 com

从数据库查询权限信息

      代码实现

        我们只需要根据用户id去查询到其所对应的权限信息即可。

​           所以我们可以先定义个mapper,其中提供一个方法可以根据userid查询权限信息。

package com.example.qinghuatokendemo.Mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.qinghuatokendemo.Domain.Menu;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;
@Mapper
public interface MenuMapper extends BaseMapper<Menu> {

    List<String> selectPermsByUserId(Long userid);

}

尤其是自定义方法,所以需要创建对应的mapper文件,定义对应的sql语句

<?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.example.qinghuatokendemo.Mapper.MenuMapper">
    <select id="selectPermsByUserId" resultType="java.lang.String">
        SELECT
            DISTINCT m.`perms`
        FROM
            sys_user_role ur
                LEFT JOIN `sys_role` r ON ur.`role_id` = r.`id`
                LEFT JOIN `sys_role_menu` rm ON ur.`role_id` = rm.`role_id`
                LEFT JOIN `sys_menu` m ON m.`id` = rm.`menu_id`
        WHERE
            user_id = #{userid}
          AND r.`status` = 0
          AND m.`status` = 0
    </select>
</mapper>

在application.yml中配置mapperXML文件的位置

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/springsecurity?characterEncoding=utf-8&serverTimezone=UTC
    username: root
    password: njzyb555
    driver-class-name: com.mysql.cj.jdbc.Driver
mybatis-plus:
  mapper-locations: classpath*:/mapper/**/*.xml

 

测试类

package com.example.qinghuatokendemo;


import com.example.qinghuatokendemo.Domain.User;
import com.example.qinghuatokendemo.Mapper.MenuMapper;
import com.example.qinghuatokendemo.Mapper.UserMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.util.List;

@SpringBootTest
public class MapperTest {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MenuMapper menuMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Test
    public void TestBCryptPasswordEncoder(){
        //$2a$10$9CmQULPcw8prFL.gnmM/zO1bDtPtVNb4mTxNs2wHsm7xonGMCvT2C

        System.out.println(passwordEncoder.
                matches("1234", "$2a$10$eAQvguaa3mHMt7cUrXeQnu3vIw74tbNtthm/t1gH6IMrRihv1OpRu"));
        /*String encode = passwordEncoder.encode("1234");
        System.out.println(encode);*/
    }

    @Test
    public void testUser(){
        List<User> users = userMapper.selectList(null);
        System.out.println(users);
    }


    @Test
    public void testselectPermsByUserId(){
        List<String> list = menuMapper.selectPermsByUserId(1L);
        System.out.println(list);
    }
}

 

 

 

自定义失败处理

  

​ 我们还希望在认证失败或者是授权失败的情况下也能和我们的接口一样返回相同结构的json,这样可以让前端能对响应进行统一的处理。要实现这个功能我们需要知道SpringSecurity的异常处理机制。

​ 在SpringSecurity中,如果我们在认证或者授权的过程中出现了异常会被ExceptionTranslationFilter捕获到。在ExceptionTranslationFilter中会去判断是认证失败还是授权失败出现的异常。

​ 如果是认证过程中出现的异常会被封装成AuthenticationException然后调用AuthenticationEntryPoint对象的方法去进行异常处理。

​ 如果是授权过程中出现的异常会被封装成AccessDeniedException然后调用AccessDeniedHandler对象的方法去进行异常处理。

​ 所以如果我们需要自定义异常处理,我们只需要自定义AuthenticationEntryPoint和AccessDeniedHandler然后配置给SpringSecurity即可。

自定义实现类

package com.example.qinghuatokendemo.Handler;

import com.alibaba.fastjson.JSON;
import com.example.qinghuatokendemo.Domain.ResponseResult;
import com.example.qinghuatokendemo.Utils.WebUtils;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class AccessDeniedHandlerImpl implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        ResponseResult result = new ResponseResult(HttpStatus.INTERNAL_SERVER_ERROR.value(),"用户认证失败请查询登录");
        String json = JSON.toJSONString(request);
        //处理异常
        WebUtils.renderString(response,json);
    }
}

 

package com.example.qinghuatokendemo.Handler;

import com.alibaba.fastjson.JSON;
import com.example.qinghuatokendemo.Domain.ResponseResult;
import com.example.qinghuatokendemo.Utils.WebUtils;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class AccessDeniedHandlerImpl implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        ResponseResult result = new ResponseResult(HttpStatus.FORBIDDEN.value(), "权限不足");
        String json = JSON.toJSONString(result);
        WebUtils.renderString(response,json);

    }
}

 

package com.example.qinghuatokendemo.Config;

import com.example.qinghuatokendemo.Handler.AccessDeniedHandlerImpl;
import com.example.qinghuatokendemo.filter.JwtAuthenticationTokenFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Autowired
    JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;

    @Autowired
    private AuthenticationEntryPoint authenticationEntryPoint;

    @Autowired
    private AccessDeniedHandler accessDeniedHandler;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
       /* http
                //关闭csrf
                .csrf().disable()
                //不通过Session获取SecurityContext
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                // 对于登录接口 允许匿名访问
                .antMatchers("/user/login").anonymous()
                // 除上面外的所有请求全部需要鉴权认证
                .anyRequest().authenticated();*/
        http
                .csrf().disable()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                .antMatchers("/hello").permitAll()
                .antMatchers("/user/login").anonymous()
                .anyRequest().authenticated();


        //把token校验过滤器添加到过滤器链中
        http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);

        //配置异常处理器
        http.exceptionHandling()
                //认证失败处理器
                .authenticationEntryPoint(authenticationEntryPoint).accessDeniedHandler(accessDeniedHandler);
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
}

 

 

 

 

 

 

标签:自定义,qinghuatokendemo,数据库,springframework,org,import,security,权限,com
From: https://www.cnblogs.com/x3449/p/17355113.html

相关文章

  • node同步查询数据库(mysql)
    mysql模块默认异步操作,在写一些简单脚本时会比较痛苦,可以通过async/await和Promise封装成同步操作asyncfunctionquery(connection,sql){returnnewPromise((resolve,reject)=>{connection.query(sql,function(error,results){if(error)reject(resu......
  • 自定义实现SpringBoot Starter
    在日常的开发中,会将开发的公共jar包发布的仓库,这样可以实现代码的复用。这里介绍的是自定义SpringBootStarter的方式,对于采用SpringBoot开发的项目来说,引入和使用非常的方便。1、SpringBootStarter介绍SpringBoot和Spring相比,在配置上简化了很多,核心就是因为Starter引入了一些......
  • sql数据库连接
    前言作为数据存储的数据库,近年来发展飞快,在早期的程序自我存储到后面的独立出中间件服务,再到集群,不可谓不快了。早期的sql数据库一枝独秀,到后面的Nosql,还有azure安全,五花八门,教人学不过来阿。一mysql数据库的golang操作针对数据库操作,往往需要安装实体数据库和对应的数据库驱......
  • P.22-认证配置详解、P.23-权限系统的作用、P.24-授权基本流程
    P.22-认证配置详解在SecurityConfig下进行修改@ConfigurationpublicclassSecurityConfigextendsWebSecurityConfigurerAdapter{//创建BCryptPasswordEncoder注入容器@BeanpublicPasswordEncoderpasswordEncoder(){returnnewBCryptPasswordEn......
  • go之logrus自定义日志样式
    日志功能配置:logrus.gopackagecoreimport("bytes""fmt""github.com/sirupsen/logrus""io""os""path")const(red=31yellow=33blue=36gray......
  • 权限模型与建表及SQL语句编写
    权限模型RBAC权限模型​RBAC权限模型(Role-BasedAccessControl)即:基于角色的权限控制。这是目前最常被开发者使用也是相对易用、通用权限模型。 准备工作      菜单表实体类}  建表及SQL语句编......
  • JDBC访问数据库
    下载,安装MySQL(下载地址:https://www.mysql.com/downloads/)创建数据库——createdatabase<数据库名>创建用户——mysql>grantallprivilegeson数据库名.*to新用户名@locahost identifiedby‘密码’;使用DDL创建表——createtable表名(字段名数据类型是否主键/非空)使用DML操......
  • 数据库实践课
    一、实验目的:掌握使用SQL语言进行数据定义和数据操纵的方法。二、实验要求:建立一个数据库stumanage,建立三个关系表student,course,sc。向表中插入数据,然后对数据进行删除、修改等操作,对关系、数据库进行删除操作。三、实验步骤:1、开始→程序→MicrosoftSQLServer→SQL......
  • django admin 中对自定义字段进行搜索
    我想在djangoadmin中使用investment字段进行搜索,但总是得到Cannotresolvekeyword'investment'intofield.选项是Model字段。有什么方法可以使用investment字段进行搜索?fromdjango.db.modelsimportCountclassReportsAdmin(admin.ModelAdmin):definvestmen......
  • Android开发之一:10.0 USB弹窗权限流程解析
    1.新建activity,获取UsbManagerusbManager=(UsbManager)getSystemService(Context.USB_SERVICE)2.获取所以的USB设备HashMap<String,UsbDevice>map=usbManager.getDeviceList()3.过滤别的USB设备,拿到自己USB的USBDevice类,然后请求USB权限,usbManager.requestPermission(us......