【Spring-Security】Re06 自定义Access & 注解权限分配
一、基于ACCESS方法处理的实现:
我们之前使用的任何放行规则的方法,本质上还是调用access方法执行的

这也意味之我们可以直接使用access方法去方向,只需要注入不同的字符串即可
自定义Access实现:
业务层自定义接口:
package cn.zeal4j.service; import org.springframework.security.core.Authentication; import javax.servlet.http.HttpServletRequest; /**
* @author Administrator
* @file IntelliJ IDEA Spring-Security-Tutorial
* @create 2020 09 28 20:17
*/
public interface CustomService {
Boolean hasPermission(HttpServletRequest httpServletRequest, Authentication authentication);
}
实现类:
package cn.zeal4j.service; import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails; import javax.servlet.http.HttpServletRequest;
import java.util.Collection; /**
* @author Administrator
* @file IntelliJ IDEA Spring-Security-Tutorial
* @create 2020 09 28 20:20
*/
public class CustomServiceImpl implements CustomService{
@Override
public Boolean hasPermission(HttpServletRequest httpServletRequest, Authentication authentication) {
// 用户信息对象
Object principal = authentication.getPrincipal(); if (principal instanceof UserDetails) { UserDetails userDetails = (UserDetails) principal; Collection<? extends GrantedAuthority> authorities = userDetails.getAuthorities(); return authorities.contains(new SimpleGrantedAuthority(httpServletRequest.getRequestURI()));
}
return false;
}
}
Access配置:
package cn.zeal4j.configuration; import cn.zeal4j.handler.CustomAccessDeniedHandler;
import cn.zeal4j.handler.FarsAuthenticationFailureHandler;
import cn.zeal4j.handler.FarsAuthenticationSuccessHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.access.AccessDeniedHandler; /**
* @author Administrator
* @file IntelliJ IDEA Spring-Security-Tutorial
* @create 2020 09 27 21:55
*/
@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter { @Autowired
private AccessDeniedHandler accessDeniedHandler; @Bean
public PasswordEncoder getPasswordEncoder() {
return new BCryptPasswordEncoder();
} @Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.formLogin(). // 设置登陆行为方式为表单登陆
// 登陆请求参数设置
usernameParameter("username").
passwordParameter("password").
loginPage("/login.html"). // 设置登陆页面URL路径
loginProcessingUrl("/login.action"). // 设置表单提交URL路径
// successForwardUrl("/main.page"). // 设置认证成功跳转URL路径 POST请求
successHandler(new FarsAuthenticationSuccessHandler("https://www.acfun.cn/")). // 使用自定义的重定向登陆
// failureForwardUrl("/error.page"); // 设置认证失败跳转URL路径 POST请求
failureHandler(new FarsAuthenticationFailureHandler("/error.html")); // 跨域处理,不需要跳转了 httpSecurity.authorizeRequests().
regexMatchers(HttpMethod.POST, "正则表达式").permitAll(). // 还可以对符合正则表达式的请求方式进行要求,这个属性使用来制定请求的方式
antMatchers("/**/*.js", "/**/*.css", "/**/images/*.*").permitAll(). // 静态资源放行
antMatchers("/login.html").permitAll(). // 登陆页面允许任意访问
antMatchers("/error.html").permitAll(). // 失败跳转后重定向的页面也需要被允许访问
antMatchers("/admin.page").hasAnyAuthority("admin").
/*antMatchers("/vip-01.page").hasAnyAuthority("vip-01").*/
antMatchers("/vip-01.page").hasRole("vip-01").
antMatchers("/ip.page").hasIpAddress("192.168.43.180").
// mvcMatchers("/main.page").servletPath("/xxx").permitAll(). // mvcMatchers资源放行匹配
// antMatchers("/xxx/main.page").permitAll(). // 或者多写MSP的前缀
anyRequest().authenticated(). // 其他请求均需要被授权访问
anyRequest().access("@customServiceImpl.hasPermission(httpServletRequest, authentication)"); // 自定义Access配置 // CSRF攻击拦截关闭
httpSecurity.csrf().disable(); httpSecurity.exceptionHandling().accessDeniedHandler(accessDeniedHandler); }
}
这个授权逻辑只允许赋予了对应的接口地址和的才能访问,像默认访问的index页面就会报错

二、@Secured注解:
package org.springframework.security.access.annotation; import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target; @Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface Secured {
String[] value();
}
该注解可以标记的位置,方法和类上面
可以声名的值是一个字符串数组
官方的解释:
用于声名角色权限控制,判断访问此方法是否具备注解中的角色,参数值必须以ROLE_开头
具体使用:


二、@PreAuthorize & @PostAuthorize:
@PreAuthorize 用于在方法或者类之前先判断权限,参数和access方法相同
@PostAuthorize 恰恰相反,在方法和类执行之后判断
使用这些注解需要在启动类中打上@EnableGlobalMethodSecurity

内部字符串会被读取到,和在配置类中设置是差不多的

当然和配置类不同的是,该注解允许方法注入大写的角色权限前缀,例如ROLE_vip-01
【Spring-Security】Re06 自定义Access & 注解权限分配的更多相关文章
- Spring Security实现基于RBAC的权限表达式动态访问控制
昨天有个粉丝加了我,问我如何实现类似shiro的资源权限表达式的访问控制.我以前有一个小框架用的就是shiro,权限控制就用了资源权限表达式,所以这个东西对我不陌生,但是在Spring Securit ...
- spring security采用自定义登录页和退出功能
更新... 首先采用的是XML配置方式,请先查看 初识Spring security-添加security 在之前的示例中进行代码修改 项目结构如下: 一.修改spring-security.xml ...
- spring security 3 自定义认证,授权示例
1,建一个web project,并导入所有需要的lib. 2,配置web.xml,使用Spring的机制装载: <?xml version="1.0" encoding=& ...
- 基于Spring Security 的JSaaS应用的权限管理
1. 概述 权限管理,一般指根据系统设置的安全规则或者安全策略,用户可以访问而且只能访问自己被授权的资源.资源包括访问的页面,访问的数据等,这在传统的应用系统中比较常见.本文介绍的则是基于Saas系统 ...
- spring security实现动态配置url权限的两种方法
缘起 标准的RABC, 权限需要支持动态配置,spring security默认是在代码里约定好权限,真实的业务场景通常需要可以支持动态配置角色访问权限,即在运行时去配置url对应的访问角色. 基于s ...
- [转]Spring Security 可动态授权RBAC权限模块实践
RBAC:基于角色的访问控制(Role-Based Access Control) 先在web.xml 中配置一个过滤器(必须在Struts的过滤器之前) <filter> <fil ...
- SpringBoot Spring Security 核心组件 认证流程 用户权限信息获取详细讲解
前言 Spring Security 是一个安全框架, 可以简单地认为 Spring Security 是放在用户和 Spring 应用之间的一个安全屏障, 每一个 web 请求都先要经过 Sprin ...
- Spring Security实现统一登录与权限控制
1 项目介绍 最开始是一个单体应用,所有功能模块都写在一个项目里,后来觉得项目越来越大,于是决定把一些功能拆分出去,形成一个一个独立的微服务,于是就有个问题了,登录.退出.权限控制这些东西怎么办呢? ...
- spring security使用自定义登录界面后,不能返回到之前的请求界面的问题
昨天因为集成spring security oauth2,所以对之前spring security的配置进行了一些修改,然后就导致登录后不能正确跳转回被拦截的页面,而是返回到localhost根目录. ...
- Spring Security之动态配置资源权限
在Spring Security中实现通过数据库动态配置url资源权限,需要通过配置验证过滤器来实现资源权限的加载.验证.系统启动时,到数据库加载系统资源权限列表,当有请求访问时,通过对比系统资源权限 ...
随机推荐
- [SWPUCTF 2021 新生赛]easy_sql
这道题呢就是很简单的sql注入,我们直接用sqlmap来跑. 首先我们打开页面可以看见提示,参数为wllm **然后我们启动虚拟机,输入sqlmap的命令:sqlmap -u "url地址/ ...
- ASP.NET MVC 出现: Uncaught ReferenceError: $ is not defined
ASP.NET MVC 出现: Uncaught ReferenceError: $ is not defined 错误 将 _Layout.cshtml 中的三行代码,移动到 <head> ...
- 前台往后台传id
js页面var stuid;$(function () { var request = { QueryString : function(val) { var uri = window.locatio ...
- 增补博客 第八篇 python 中国大学排名数据分析与可视化
[题目描述]以软科中国最好大学排名为分析对象,基于requests库和bs4库编写爬虫程序,对2015年至2019年间的中国大学排名数据进行爬取:(1)按照排名先后顺序输出不同年份的前10位大学信息, ...
- java.sql.SQLException: Connection is read-only. Queries leading to data modification are not
java.sql.SQLException: Connection is read-only. Queries leading to data modification are not 产生的原因:事 ...
- Python 安装 matlabengin 时遇到报错:setup.py install is deprecated. !! 以及 Cannot update time stamp of directory 'dist\matlabengine.egg-info' 的解决方案
目录 Python 安装 matlabengin 时遇到报错:setup.py install is deprecated. !! 以及 Cannot update time stamp of dir ...
- vue.config.js配置优化
vue.config.js完整代码如下: 'use strict'; // Template version: 1.3.1 // see http://vuejs-templates.github.i ...
- Jenkins从github拉取项目,github有更新,自动进行构建,实现自动集成
使用git之前的准备工作 1. 搭建Jenkins的机器上,有安装git,配置git的安装地址,Jenkins配置Git的安装地址 2. Global Tool Configuration - > ...
- mysql+redis点赞功能剖析
最近在一个应用上需要用到点赞的功能,因为点赞的功能比较常用,很多人看到了大拇指就点了上去,如果单单采用mysql的方式的话可以会对数据库造成很大的压力. 我看了下网上一些博主的提供的解决方案,主要以m ...
- 高通安卓:自定义QFile烧录镜像
高通安卓:自定义QFile烧录镜像 背景 在某个项目中,因为USB口的问题,无法使用fastboot进行download. 同事提供了一份用与QFile的rawprogram.xml烧写.觉得这个方法 ...