首页 > 其他分享 >Spring Security - authorization

Spring Security - authorization

时间:2023-08-16 20:32:19浏览次数:42  
标签:权限 Spring response role id Security configuration public authorization

前面我们弄好了认证,授权就是在认证的基础之上

授权

只有用户认证了才可能有授权,授权就是当前用户能干什么

UserDetailServiceImpl

	// 之前我们只是在这里将用户的一些基本信息封装了,但是我们要授权的话需要角色信息和权限信息
	// TODO 添加持久层的代码 获取当前用户的角色和权限信息

TokenFilter

	// 在对UsernamePasswordAuthenticationToken封装的时候,没有将对象中的权限封装进去

	// TODO 调用UserDetail中的getAuthorities方法,这个方法返回GrantedAuthority
	UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, null,loginUser.getAuthorities());
       

启动类

添加@EnableGlobalMethodSecurity(prePostEnabled = true)注解

Controller

在Controller层中的方法上添加 @PreAuthorize("hasAuthority('权限名')") @PreAuthorize("hasAuthority('权限名')") 用户有这个权限才能访问 @PreAuthorize("hasRole('角色名')") 用户是当前角色才能访问

RBAC模型

基于角色进行权限控制,这个时候我们不关心当前用户有哪些权限。只用关系当前用户有哪些角色

RBAC表设计

  1. tb_security_user_role
    • id
    • user_id
    • role_id
  2. tb_security_role
    • id
    • role_name
  3. tb_security_role_permission
    • id
    • role_id
    • permission_id
  4. tb_security_permission
    • id
    • permission_name

其他

自定义处理异常

当发送异常的时候,SepringSecurity会自动处理掉。因为我们是前后端分离我们不用管处理的逻辑只用返回一个Result的json字符串返回给前端,前端自己处理

{
	"code" : "xxx",
	"msg"  : "xxx",
	"status" : "xxx",
	"data" : [
		"key" : "value"
	]
}

自定义处理认证时发送的异常

@Component
// 认证期间异常处理
public class AuthenticationExceptionHandler implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        Result result = Result.fail().data("msg", authException.getMessage());
        String resultJSON = JSONUtil.toJsonStr(result);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter writer = response.getWriter();

        writer.append(resultJSON);

    }
}

自定义授权时发生的异常

@Component
// 处理授权异常的
public class AuthorizationExceptionHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        Result result = Result.fail().data("msg", accessDeniedException.getMessage());
        String resultJSON = JSONUtil.toJsonStr(result);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter writer = response.getWriter();

        writer.append(resultJSON);
    }
}

将自定义的处理异常对象添加到配置类中 SecurityConfig

 	// 自定义异常处理
        http.exceptionHandling()
                .authenticationEntryPoint(authenticationExceptionHandler)
                .accessDeniedHandler(authorizationExceptionHandler);

跨域

解决Spring Security跨域 SecurityConfig

  	// 跨域
        http.cors();

解决MVC跨域

@Configuration
public class CorsConfig {

    @Bean
    public CorsConfigurationSource corsFilterConfiguration() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.addAllowedOrigin("*"); // 允许所有源
        configuration.addAllowedHeader("*"); // 允许所有请求头
        configuration.addAllowedMethod("*"); // 允许所有请求方法
        configuration.setAllowCredentials(true); // 允许发送凭证
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration); // 对所有URL生效
        return source;
    }
}

标签:权限,Spring,response,role,id,Security,configuration,public,authorization
From: https://blog.51cto.com/u_15497049/7113217

相关文章

  • Spring Security - authentication
    前言:SpringSecurity是Spring家族中的安全框架,主要功能有两个认证(authentication)授权(authorization)认证认证核心过滤器链流程图前端发送请求AuthenticationFilter拦截请求调用UsernamePassowordAuthenticationTokenUsernamePassowordAuthenticationToken将前端发送的表......
  • spring注入bean错误-Bean named 'abc' is expected to be of type 'AAA' but was actu
    先看如下两个注入到spring容器中的bean,一个是UserNewManager,一个是UserManager。@ServicepublicclassUserNewManager{publicvoiddoSomething(){}}@ServicepublicclassUserManager{...}再看下面的testcase,利用@Resource注解来注入bean。@......
  • springmvc 使用 DeferredResult
    背景:需求:可以实时获取啄木鸟伍迪的访问数据、排名、积分等数据,可以实时现在在网站后台页面的大屏上;解决方案:可以使用异步请求,springmvc默认的请求都是同步的,也就是请求过去,必须得有处理完成,否则就回阻塞;异步请求是当发起一个请求,可以暂时没有响应,请求回被挂起不阻塞;请求过去,就......
  • 深入解析Spring Boot自动配置原理
    大家好,我是你的技术达人小助手,在今天的技术博客中,我将带你深入解析SpringBoot自动配置的原理,揭示其神秘面纱,让你能更好地理解和利用这一强大的功能。准备好了吗?让我们一起开始这次关于SpringBoot自动配置的探索之旅吧!背景知识SpringBoot作为一款优秀的Java开发框架,以其方便的配......
  • 深入探索Spring Cloud微服务架构
    嗨,亲爱的读者朋友们!今天,我将带你深入探索SpringCloud微服务架构的精髓,解析其在现代分布式系统中的重要地位。作为一个技术达人,我将从基本概念到核心组件,带你领略SpringCloud的魔力,让你在微服务世界中游刃有余。微服务架构的背景在现代应用开发中,微服务架构越来越受欢迎。它通过将......
  • 解密Spring Framework的核心原理与魔法
    嗨,亲爱的读者朋友们!今天,我将带你解密SpringFramework的核心原理与魔法,帮助你深入理解这个强大的Java开发框架。作为一个技术达人,我将为你揭开SpringFramework的神秘面纱,让你在开发中游刃有余。SpringFramework简介SpringFramework是一个全面的、模块化的Java开发框架,被广泛用于......
  • 构建高性能微服务架构:深入探索Spring Cloud与Spring Boot
    嗨,亲爱的读者朋友们!今天,我将带你深入探索如何通过SpringCloud和SpringBoot构建高性能微服务架构,为你揭示这个充满活力和机遇的技术领域。作为一个技术达人,我将从基本概念到关键组件,为你展示如何在现代应用开发中构建强大的微服务架构。微服务架构的兴起微服务架构正以惊人的速度......
  • 构建高性能微服务架构:深入探索Spring Cloud与Spring Boot
    嗨,亲爱的读者朋友们!今天,我将带你深入探索如何通过SpringCloud与SpringBoot构建高性能微服务架构,为你揭示这个充满活力与机遇的技术领域。作为一个技术达人,我将从基础概念到关键组件,为你呈现如何在现代应用开发中构建强大的微服务架构。微服务架构的兴起微服务架构正以惊人的速度......
  • springmvc 开启异步请求报错 Java code using the Servlet API or by adding "true"
    报错内容:java.lang.IllegalStateException:Asyncsupportmustbeenabledonaservletandforallfiltersinvolvedinasyncrequestprocessing.ThisisdoneinJavacodeusingtheServletAPIorbyadding"true"toservletandfilterdeclarationsin......
  • spring-boot静态资源目录配置
    spring-boot静态资源目录配置spring-boot静态资源默认为/src/main/resources下的/static目录,可以通过application.properties的server.servlet.context-path属性配置如:server.servlet.context-path=/public......