Spring Security构建Rest服务-1400-授权
安全分为 认证和授权,前边讲的都是认证,现在说授权。
前端业务系统的权限简单些,一般只区分是否登录,复杂点的还会区分 VIP用户等简单的角色,权限规则基本不变。
后台系统比较复杂,角色众多,权限随着业务不断变化。

1,用代码控制简单的权限
直接在配置类 BrowserSecurityConfig extends WebSecurityConfigurerAdapter 的configure方法里
http //--------------授权相关的配置 ---------------------
.authorizeRequests()
// /authentication/require:处理登录,securityProperties.getBrowser().getLoginPage():用户配置的登录页
.antMatchers(SecurityConstants.DEFAULT_UNAUTHENTICATION_URL,
securityProperties.getBrowser().getLoginPage(),//放过登录页不过滤,否则报错
SecurityConstants.DEFAULT_LOGIN_PROCESSING_URL_MOBILE,
SecurityConstants.SESSION_INVALID_PAGE,
SecurityConstants.DEFAULT_VALIDATE_CODE_URL_PREFIX+"/*")//验证码
.permitAll() //-------上边的不用授权也允许访问------
//~=========简单的权限控制,只区分是否登录的情况可以配置在这里=======
// /user 的post请求需要ADMIN权限
.antMatchers("/user/*").hasRole("ADMIN")
.anyRequest() //任何请求
.authenticated() //都需要身份认证
一行红色部分配置就可以了,意思是 /user/* 的所有请求需要有ADMIN 权限,如果是Rest风格的服务,只需要配置成 antMatchers(HttpMethod.POST,"/user/*").hasRole("ADMIN") 格式即可。
这个权限在UserDetailsService 的loadUserByUsername方法返回的user的权限集合里定义。格式是ROLE_ADMIN( ROLE_权限名称,ADMIN和匹配器里一致)(这个格式具体在ExpressionUrlAuthorizationConfigurer里)
private SocialUserDetails buildUser(String userId) {
String password = passwordEncoder.encode("123456");
System.err.println("加密后密码: "+password);
//参数:用户名|密码|是否启用|账户是否过期|密码是否过期|账户是否锁定|权限集合
return new SocialUser(userId,password,true,true,true,true,
//工具类 将字符串转换为权限集合,ROLE_角色 是spring要求的权限格式
AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_ADMIN"));
}

再说一个过滤器,AnonymousAuthenticationFilter,这个过滤器就是判断前边的过滤器是否认证成功,如果没有认证成功,就创建一个默认的用户创建一个Authentication 做登录。具体代码看其源码。
SpringSecurity 授权相关类

==============================================================================================================================
控制复杂权限:基于rbac
自定义查询权限的类根据用户名查询用户的权限
package com.imooc.security.rbac; import java.util.HashSet;
import java.util.Set; import javax.servlet.http.HttpServletRequest; import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher; @Component("rbacService")
public class RbacServiceImpl implements RbacService { private AntPathMatcher antPathMatcher = new AntPathMatcher(); @Override
public boolean hasPermission(HttpServletRequest request, Authentication authentication) { Object principal = authentication.getPrincipal(); boolean hasPermission = false; if(principal instanceof UserDetails){ String username = ((UserDetails)principal).getUsername(); //读取用户所有权限的url,需要查询数据库
Set<String> urls = new HashSet<>();
urls.add("/user/*"); for(String url : urls){
if(antPathMatcher.match(url, request.getRequestURI())){
hasPermission = true ;
break ;
}
}
}
return hasPermission;
} }
配置,注意,授权的配置要配置在免登录就能访问的服务器的最后

github:https://github.com/lhy1234/spring-security
Spring Security构建Rest服务-1400-授权的更多相关文章
- Spring Security构建Rest服务-1300-Spring Security OAuth开发APP认证框架之JWT实现单点登录
基于JWT实现SSO 在淘宝( https://www.taobao.com )上点击登录,已经跳到了 https://login.taobao.com,这是又一个服务器.只要在淘宝登录了,就能直接访 ...
- Spring Security构建Rest服务-1202-Spring Security OAuth开发APP认证框架之重构3种登录方式
SpringSecurityOAuth核心源码解析 蓝色表示接口,绿色表示类 1,TokenEndpoint 整个入口点,相当于一个controller,不同的授权模式获取token的地址都是 /oa ...
- Spring Security构建Rest服务-1001-spring social开发第三方登录之spring social基本原理
OAuth协议是一个授权协议,目的是让用户在不将服务提供商的用户名密码交给第三方应用的条件下,让第三方应用可以有权限访问用户存在服务提供商上的资源. 接着上一篇说的,在第三方应用获取到用户资源后,如果 ...
- Spring Security构建Rest服务-1201-Spring Security OAuth开发APP认证框架之实现服务提供商
实现服务提供商,就是要实现认证服务器.资源服务器. 现在做的都是app的东西,所以在app项目写代码 认证服务器: 新建 ImoocAuthenticationServerConfig 类,@Ena ...
- Spring Security构建Rest服务-1200-SpringSecurity OAuth开发APP认证框架
基于服务器Session的认证方式: 前边说的用户名密码登录.短信登录.第三方登录,都是普通的登录,是基于服务器Session保存用户信息的登录方式.登录信息都是存在服务器的session(服务器的一 ...
- Spring Security构建Rest服务-0900-rememberMe记住我
Spring security记住我基本原理: 登录的时候,请求发送给过滤器UsernamePasswordAuthenticationFilter,当该过滤器认证成功后,会调用RememberMeS ...
- Spring Security构建Rest服务-1205-Spring Security OAuth开发APP认证框架之Token处理
token处理之二使用JWT替换默认的token JWT(Json Web Token) 特点: 1,自包含:jwt token包含有意义的信息 spring security oauth默认生成的t ...
- Spring Security构建Rest服务-1204-Spring Security OAuth开发APP认证框架之Token处理
token处理之一基本参数配置 处理token时间.存储策略,客户端配置等 以前的都是spring security oauth默认的token生成策略,token默认在org.springframe ...
- Spring Security构建Rest服务-0702-短信验证码登录
先来看下 Spring Security密码登录大概流程,模拟这个流程,开发短信登录流程 1,密码登录请求发送给过滤器 UsernamePasswordAuthenticationFilter 2,过 ...
- Spring Security构建Rest服务-0800-Spring Security图片验证码
验证码逻辑 以前在项目中也做过验证码,生成验证码的代码网上有很多,也有一些第三方的jar包也可以生成漂亮的验证码.验证码逻辑很简单,就是在登录页放一个image标签,src指向一个controller ...
随机推荐
- Spring3.x错误---- Cannot proxy target class because CGLIB2 is not available. Add CGLIB to the class path or specify proxy interfaces.
Spring3.x错误: 解决方法: 缺少cglib的包, 下载地址: http://sourceforge.net/projects/cglib/files/latest/download?sour ...
- 20155218 2016-2017-2 《Java程序设计》第10周学习总结
20155218 2016-2017-2 <Java程序设计>第10周学习总结 教材学习内容总结 一个IP地址可以对应多个域名,一个域名只能对应一个IP地址. 在网络通讯中,第一次主动发起 ...
- x+y+z=n的正整数解
题:x+y+z=n,其中(n>=3),求x,y,z的正整数解的个数根据图象法:x>=1,y>=1,x+y<=n-1
- 201709012工作日记--Android消息机制
1. android的消息机制——Handler机制 参考:http://www.jianshu.com/p/9e4d1fab0f36. Android异步消息处理机制完全解析,带你从源码的角度理解: ...
- POJ3104 Drying 2017-05-09 23:33 41人阅读 评论(0) 收藏
Drying Time Limit: 2000MS Memory Limit: 65536K Total Submissions: 15604 Accepted: 3976 Descripti ...
- Codeforces777C Alyona and Spreadsheet 2017-05-04 17:46 103人阅读 评论(0) 收藏
C. Alyona and Spreadsheet time limit per test 1 second memory limit per test 256 megabytes input sta ...
- linux处理U盘中的资料-挂载-tar.gz软件安装-linux环境下软件的安装方式
1. U盘插入linux一般会有以下反映 (1)/dev 的目录下,多出一个sdb的磁盘. 因为:目前系统中有两个硬盘, sda是原来的系统磁盘.sdb是插入的U盘. 其中:sdb1表示sdbU盘的一 ...
- POJ1062不错的题——spfa倒向建图——枚举等级限制
POJ1062 虽然是中文题目但是还是有一定几率都不准题目意思的:1.所有可能降价的措施不是降价多少钱而是降至多少钱2.等级范围:是你所走的那一条路中所有人中最好最低等级差不允许超过limit限制 思 ...
- c#字典怎么获取第一个键值 List<对象>获取重复项,转成Dictionary<key,List<对象>>
c#字典怎么获取第一个键值 Dictionary<string, int> dictionary = new Dictionary<string, int>(); dictio ...
- 深入学习c++--智能指针(一) shared_ptr
1. 几种智能指针 1. auto_ptr: c++11中推荐不使用他 2. shared_ptr: 每添加一次引用 就+1,减少一次引用,就-1:做到指针进行共享 3. unique_ptr: 一个 ...