安全分为 认证和授权,前边讲的都是认证,现在说授权。

前端业务系统的权限简单些,一般只区分是否登录,复杂点的还会区分 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-授权的更多相关文章

  1. Spring Security构建Rest服务-1300-Spring Security OAuth开发APP认证框架之JWT实现单点登录

    基于JWT实现SSO 在淘宝( https://www.taobao.com )上点击登录,已经跳到了 https://login.taobao.com,这是又一个服务器.只要在淘宝登录了,就能直接访 ...

  2. Spring Security构建Rest服务-1202-Spring Security OAuth开发APP认证框架之重构3种登录方式

    SpringSecurityOAuth核心源码解析 蓝色表示接口,绿色表示类 1,TokenEndpoint 整个入口点,相当于一个controller,不同的授权模式获取token的地址都是 /oa ...

  3. Spring Security构建Rest服务-1001-spring social开发第三方登录之spring social基本原理

    OAuth协议是一个授权协议,目的是让用户在不将服务提供商的用户名密码交给第三方应用的条件下,让第三方应用可以有权限访问用户存在服务提供商上的资源. 接着上一篇说的,在第三方应用获取到用户资源后,如果 ...

  4. Spring Security构建Rest服务-1201-Spring Security OAuth开发APP认证框架之实现服务提供商

    实现服务提供商,就是要实现认证服务器.资源服务器. 现在做的都是app的东西,所以在app项目写代码  认证服务器: 新建 ImoocAuthenticationServerConfig 类,@Ena ...

  5. Spring Security构建Rest服务-1200-SpringSecurity OAuth开发APP认证框架

    基于服务器Session的认证方式: 前边说的用户名密码登录.短信登录.第三方登录,都是普通的登录,是基于服务器Session保存用户信息的登录方式.登录信息都是存在服务器的session(服务器的一 ...

  6. Spring Security构建Rest服务-0900-rememberMe记住我

    Spring security记住我基本原理: 登录的时候,请求发送给过滤器UsernamePasswordAuthenticationFilter,当该过滤器认证成功后,会调用RememberMeS ...

  7. Spring Security构建Rest服务-1205-Spring Security OAuth开发APP认证框架之Token处理

    token处理之二使用JWT替换默认的token JWT(Json Web Token) 特点: 1,自包含:jwt token包含有意义的信息 spring security oauth默认生成的t ...

  8. Spring Security构建Rest服务-1204-Spring Security OAuth开发APP认证框架之Token处理

    token处理之一基本参数配置 处理token时间.存储策略,客户端配置等 以前的都是spring security oauth默认的token生成策略,token默认在org.springframe ...

  9. Spring Security构建Rest服务-0702-短信验证码登录

    先来看下 Spring Security密码登录大概流程,模拟这个流程,开发短信登录流程 1,密码登录请求发送给过滤器 UsernamePasswordAuthenticationFilter 2,过 ...

  10. Spring Security构建Rest服务-0800-Spring Security图片验证码

    验证码逻辑 以前在项目中也做过验证码,生成验证码的代码网上有很多,也有一些第三方的jar包也可以生成漂亮的验证码.验证码逻辑很简单,就是在登录页放一个image标签,src指向一个controller ...

随机推荐

  1. UVaLive 4597 Inspection (网络流,最小流)

    题意:给出一张有向图,每次你可以从图中的任意一点出发,经过若干条边后停止,然后问你最少走几次可以将图中的每条边都走过至少一次,并且要输出方案,这个转化为网络流的话,就相当于 求一个最小流,并且存在下界 ...

  2. cmake-include_directories

    include_directories: Add include directories to the build. include_directories([AFTER|BEFORE] [SYSTE ...

  3. python编码(二)

    谈谈Unicode编码,简要解释UCS.UTF.BMP.BOM等名词 问题一 使用Windows记事本的“另存为”,可以在GBK.Unicode.Unicode big endian和UTF-8这几种 ...

  4. 15) maven dependency scope

    Dependency Scope Dependency scope is used to limit the transitivity of a dependency, and also to aff ...

  5. 集合(四)HashMap

    之前的List,讲了ArrayList.LinkedList,最后讲到了CopyOnWriteArrayList,就前两者而言,反映的是两种思想: (1)ArrayList以数组形式实现,顺序插入.查 ...

  6. Spring Boot 2 实践记录之 使用 Powermock、Mockito 对 UUID 进行 mock 单元测试

    由于注册时,需要对输入的密码进行加密,使用到了 UUID.sha1.md 等算法.在单元测试时,使用到了 Powermock,记录如下. 先看下加密算法: import org.apache.comm ...

  7. Replication--对发布修改的一些小总结

    --==================================================== --在华丽分割线下,是我对肖磊--大菠萝的崇高地敬意和婶婶地感谢,本文乃肖兄表述我执笔而来 ...

  8. XML字符串反序列化为实体

    JSON反序列化实体 paydata = StringHelper.Base64ToString(paydata); resInfo = JsonConvert.DeserializeObject&l ...

  9. C# 实现邮件代发

    由于自己很好奇,有一些推广之类的 邮件,发件人后面,都有一个 由 .... 代发. 所以,查找了一些资料,来验证了一下实现方法. 咱们先来看看,实现代发的 理想效果图 当然,这一种,是利用 代发的 邮 ...

  10. 《Real Time Rendering》第四章 图形变换

    图形变换是一个将例如点.向量或者颜色等实体进行某种转换的操作.对于计算机图形学的先驱者,掌握图形变换是极为重要的.有了他们,你就可以对象.光源以及摄像机进行定位,变形以及动画添加.你也可以确认所有的计 ...