作者:小小____\
起源:segmentfault.com/a/1190000023052493
思维导图如下
RBAC 权限剖析
RBAC 全称为基于角色的权限管制,本段将会从什么是 RBAC,模型分类,什么是权限,用户组的应用,实例剖析等几个方面论述 RBAC
思维导图
绘制思维导图如下
什么是 RBAC
RBAC 全称为用户角色权限管制,通过角色关联用户,角色关联权限,这种形式,间阶的赋予用户的权限,如下图所示
对于通常的零碎而言,存在多个用户具备雷同的权限,在调配的时候,要为指定的用户调配相干的权限,批改的时候也要顺次的对这几个用户的权限进行批改,有了角色这个权限,在批改权限的时候,只须要对角色进行批改,就能够实现相干的权限的批改。这样做减少了效率,缩小了权限破绽的产生。
模型分类
对于 RBAC 模型来说,分为以下几个模型 别离是 RBAC0,RBAC1,RBAC2,RBAC3,这四个模型,这段将会顺次介绍这四个模型,其中最罕用的模型有 RBAC0.
RBAC0
RBAC0 是最简略的 RBAC 模型,这外面蕴含了两种。
用户和角色是多对一的关系,即一个用户只充当一种角色,一个角色能够有多个角色的担当。
用户和角色是多对多的关系,即,一个用户能够同时充当多个角色,一个角色能够有多个用户。
此零碎性能繁多,人员较少,这里举个栗子,张三既是行政,也负责财务,此时张三就有俩个权限,别离是行政权限,和财务权限两个局部。
RBAC1
绝对于 RBAC0 模型来说,减少了子角色,引入了继承的概念。
RBAC2 模型
这里 RBAC2 模型,在 RBAC0 模型的根底上,减少了一些性能,以及限度
角色互斥
即,同一个用户不能领有两个互斥的角色,举个例子,在财务零碎中,一个用户不能领有会计员和审计这两种角色。
基数束缚
即,用一个角色,所领有的成员是固定的,例如对于 CEO 这种角色,同一个角色,也只能有一个用户。
先决条件
即,对于该角色来说,如果想要取得更高的角色,须要先获取低一级别的角色。举个栗子,对于副总经理和经理这两个权限来说,须要先有副总经理权限,能力领有经理权限,其中副总经理权限是经理权限的先决条件。
运行时互斥
即,一个用户能够领有两个角色,然而这俩个角色不能同时应用,须要切换角色能力进入另外一个角色。举个栗子,对于总经理和专员这两个角色,零碎只能在一段时间,领有其一个角色,不能同时对这两种角色进行操作。
RBAC3 模型
即,RBAC1,RBAC2,两者模型全副累计,称为对立模型。
什么是权限
权限是资源的汇合,这里的资源指的是软件中的所有的内容,即,对页面的操作权限,对页面的拜访权限,对数据的增删查改的权限。举个栗子。对于下图中的零碎而言,
领有,打算治理,客户治理,合同治理,出入库通知单治理,粮食安全追溯,食粮统计查问,设施治理这几个页面,对这几个页面的拜访,以及是否可能拜访到菜单,都属于权限。
用户组的应用
对于用户组来说,是把泛滥的用户划分为一组,进行批量授予角色,即,批量授予权限。举个栗子,对于部门来说,一个部门领有一万多个员工,这些员工都领有雷同的角色,如果没有用户组,可能须要一个个的授予相干的角色,在领有了用户组当前,只须要,把这些用户全副划分为一组,而后对该组设置授予角色,就等同于对这些用户授予角色。
长处:缩小工作量,便于了解,减少多级治理,等。
SpringSecurity 简略应用
首先增加依赖
Spring Boot 根底就不介绍了,举荐下这个实战教程:
https://github.com/javastacks…
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
而后增加相干的拜访接口
package com.example.demo.web;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/test")
public class Test {@RequestMapping("/test")
public String test(){return "test";}
}
最初启动我的项目,在日志中查看相干的明码
拜访接口,能够看到相干的登录界面
输出用户名和相干的明码
用户名:user
明码 984cccf2-ba82-468e-a404-7d32123d0f9c
登录胜利
减少用户名和明码
在配置文件中,书写相干的登录和明码
spring:
security:
user:
name: ming
password: 123456
roles: admin
在登录页面,输出用户名和明码,即可失常登录
基于内存的认证
须要自定义类继承 WebSecurityConfigurerAdapter 代码如下
package com.example.demo.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@Configuration
public class MyWebSecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
PasswordEncoder passwordEncoder(){return NoOpPasswordEncoder.getInstance();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {auth.inMemoryAuthentication()
.withUser("admin").password("123").roles("admin");
}
}
即,配置的用户名为 admin,明码为 123,角色为 admin
HttpSecurity
这里对一些办法进行拦挡
package com.ming.demo.interceptor;
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.authentication.builders.AuthenticationManagerBuilder;
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.EnableWebSecurity;
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.authentication.rememberme.TokenBasedRememberMeServices;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
// 基于内存的用户存储
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {auth.inMemoryAuthentication()
.withUser("itguang").password("123456").roles("USER").and()
.withUser("admin").password("{noop}" + "123456").roles("ADMIN");
}
// 申请拦挡
@Override
protected void configure(HttpSecurity http) throws Exception {http.authorizeRequests()
.anyRequest().permitAll()
.and()
.formLogin()
.permitAll()
.and()
.logout()
.permitAll();}
}
即,这里实现了对所有的办法拜访的拦挡。
SpringSecurity 集成 JWT
这是一个小 demo,目标,登录当前返回 jwt 生成的 token
导入依赖
增加 web 依赖
导入 JWT 和 Security 依赖
<!-- https://mvnrepository.com/artifact/io.jsonwebtoken/jjwt -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-security -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
<version>2.3.1.RELEASE</version>
</dependency>
创立一个 JwtUser 实现 UserDetails
创立 一个相干的 JavaBean
package com.example.demo;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.Collection;
public class JwtUser implements UserDetails {
private String username;
private String password;
private Integer state;
private Collection<? extends GrantedAuthority> authorities;
public JwtUser(){}
public JwtUser(String username, String password, Integer state, Collection<? extends GrantedAuthority> authorities){
this.username = username;
this.password = password;
this.state = state;
this.authorities = authorities;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {return authorities;}
@Override
public String getPassword() {return this.password;}
@Override
public String getUsername() {return this.username;}
@Override
public boolean isAccountNonExpired() {return true;}
@Override
public boolean isAccountNonLocked() {return true;}
@Override
public boolean isCredentialsNonExpired() {return true;}
@Override
public boolean isEnabled() {return true;}
}
编写工具类生成令牌
编写工具类,用来生成 token,以及刷新 token,以及验证 token
package com.example.demo;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.security.core.userdetails.UserDetails;
import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class JwtTokenUtil implements Serializable {
private String secret;
private Long expiration;
private String header;
private String generateToken(Map<String, Object> claims) {Date expirationDate = new Date(System.currentTimeMillis() + expiration);
return Jwts.builder().setClaims(claims).setExpiration(expirationDate).signWith(SignatureAlgorithm.HS512, secret).compact();}
private Claims getClaimsFromToken(String token) {
Claims claims;
try {claims = Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();} catch (Exception e) {claims = null;}
return claims;
}
public String generateToken(UserDetails userDetails) {Map<String, Object> claims = new HashMap<>(2);
claims.put("sub", userDetails.getUsername());
claims.put("created", new Date());
return generateToken(claims);
}
public String getUsernameFromToken(String token) {
String username;
try {Claims claims = getClaimsFromToken(token);
username = claims.getSubject();} catch (Exception e) {username = null;}
return username;
}
public Boolean isTokenExpired(String token) {
try {Claims claims = getClaimsFromToken(token);
Date expiration = claims.getExpiration();
return expiration.before(new Date());
} catch (Exception e) {return false;}
}
public String refreshToken(String token) {
String refreshedToken;
try {Claims claims = getClaimsFromToken(token);
claims.put("created", new Date());
refreshedToken = generateToken(claims);
} catch (Exception e) {refreshedToken = null;}
return refreshedToken;
}
public Boolean validateToken(String token, UserDetails userDetails) {JwtUser user = (JwtUser) userDetails;
String username = getUsernameFromToken(token);
return (username.equals(user.getUsername()) && !isTokenExpired(token));
}
}
编写拦截器
编写 Filter 用来检测 JWT
package com.example.demo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
@Autowired
private UserDetailsService userDetailsService;
@Autowired
private JwtTokenUtil jwtTokenUtil;
@Override
protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {String authHeader = httpServletRequest.getHeader(jwtTokenUtil.getHeader());
if (authHeader != null && StringUtils.isNotEmpty(authHeader)) {String username = jwtTokenUtil.getUsernameFromToken(authHeader);
if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
if (jwtTokenUtil.validateToken(authHeader, userDetails)) {
UsernamePasswordAuthenticationToken authentication =
new UsernamePasswordAuthenticationToken(userDetails,null,userDetails.getAuthorities());
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpServletRequest));
SecurityContextHolder.getContext().setAuthentication(authentication);
}
}
}
filterChain.doFilter(httpServletRequest, httpServletResponse);
}
}
编写 userDetailsService 的实现类
在上方代码中,编写 userDetailsService,类,实现其验证过程
package com.example.demo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import javax.management.relation.Role;
import java.util.List;
@Service
public class JwtUserDetailsServiceImpl implements UserDetailsService {
@Autowired
private UserMapper userMapper;
@Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {User user = userMapper.selectByUserName(s);
if (user == null) {throw new UsernameNotFoundException(String.format("'%s'. 这个用户不存在 ", s));
}
List<SimpleGrantedAuthority> collect = user.getRoles().stream().map(Role::getRolename).map(SimpleGrantedAuthority::new).collect(Collectors.toList());
return new JwtUser(user.getUsername(), user.getPassword(), user.getState(), collect);
}
}
编写登录
编写登录业务的实现类 其 login 办法会返回一个 JWTUtils 的 token
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private UserDetailsService userDetailsService;
@Autowired
private JwtTokenUtil jwtTokenUtil;
public User findByUsername(String username) {User user = userMapper.selectByUserName(username);
return user;
}
public RetResult login(String username, String password) throws AuthenticationException {UsernamePasswordAuthenticationToken upToken = new UsernamePasswordAuthenticationToken(username, password);
final Authentication authentication = authenticationManager.authenticate(upToken);
SecurityContextHolder.getContext().setAuthentication(authentication);
UserDetails userDetails = userDetailsService.loadUserByUsername(username);
return new RetResult(RetCode.SUCCESS.getCode(),jwtTokenUtil.generateToken(userDetails));
}
}
最初配置 Config
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableWebSecurity
public class WebSecurity extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Autowired
private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;
@Autowired
public void configureAuthentication(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {authenticationManagerBuilder.userDetailsService(this.userDetailsService).passwordEncoder(passwordEncoder());
}
@Bean(name = BeanIds.AUTHENTICATION_MANAGER)
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {return super.authenticationManagerBean();
}
@Bean
public PasswordEncoder passwordEncoder() {return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {http.csrf().disable().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and().authorizeRequests()
.antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
.antMatchers("/auth/**").permitAll()
.anyRequest().authenticated()
.and().headers().cacheControl();
http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry = http.authorizeRequests();
registry.requestMatchers(CorsUtils::isPreFlightRequest).permitAll();}
@Bean
public CorsFilter corsFilter() {final UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
final CorsConfiguration cors = new CorsConfiguration();
cors.setAllowCredentials(true);
cors.addAllowedOrigin("*");
cors.addAllowedHeader("*");
cors.addAllowedMethod("*");
urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", cors);
return new CorsFilter(urlBasedCorsConfigurationSource);
}
}
运行,返回 token
运行,返回后果为 token
SpringSecurity JSON 登录
这里配置 SpringSecurity 之 JSON 登录
这里须要重写 UsernamePasswordAnthenticationFilter 类,以及配置 SpringSecurity
重写 UsernamePasswordAnthenticationFilter
public class CustomAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
//attempt Authentication when Content-Type is json
if(request.getContentType().equals(MediaType.APPLICATION_JSON_UTF8_VALUE)
||request.getContentType().equals(MediaType.APPLICATION_JSON_VALUE)){
//use jackson to deserialize json
ObjectMapper mapper = new ObjectMapper();
UsernamePasswordAuthenticationToken authRequest = null;
try (InputStream is = request.getInputStream()){AuthenticationBean authenticationBean = mapper.readValue(is,AuthenticationBean.class);
authRequest = new UsernamePasswordAuthenticationToken(authenticationBean.getUsername(), authenticationBean.getPassword());
}catch (IOException e) {e.printStackTrace();
authRequest = new UsernamePasswordAuthenticationToken("","");
}finally {setDetails(request, authRequest);
return this.getAuthenticationManager().authenticate(authRequest);
}
}
//transmit it to UsernamePasswordAuthenticationFilter
else {return super.attemptAuthentication(request, response);
}
}
}
配置 SecurityConfig
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.cors().and()
.antMatcher("/**").authorizeRequests()
.antMatchers("/", "/login**").permitAll()
.anyRequest().authenticated()
// 这里必须要写 formLogin(),不然原有的 UsernamePasswordAuthenticationFilter 不会呈现,也就无奈配置咱们从新的 UsernamePasswordAuthenticationFilter
.and().formLogin().loginPage("/")
.and().csrf().disable();
// 用重写的 Filter 替换掉原有的 UsernamePasswordAuthenticationFilter
http.addFilterAt(customAuthenticationFilter(),
UsernamePasswordAuthenticationFilter.class);
}
// 注册自定义的 UsernamePasswordAuthenticationFilter
@Bean
CustomAuthenticationFilter customAuthenticationFilter() throws Exception {CustomAuthenticationFilter filter = new CustomAuthenticationFilter();
filter.setAuthenticationSuccessHandler(new SuccessHandler());
filter.setAuthenticationFailureHandler(new FailureHandler());
filter.setFilterProcessesUrl("/login/self");
// 这句很要害,重用 WebSecurityConfigurerAdapter 配置的 AuthenticationManager,不然要本人组装 AuthenticationManager
filter.setAuthenticationManager(authenticationManagerBean());
return filter;
}
这样就实现应用 json 登录 SpringSecurity
Spring Security 明码加密形式
须要在 Config 类中配置如下内容
/**
* 明码加密
*/
@Bean
public BCryptPasswordEncoder passwordEncoder(){return new BCryptPasswordEncoder();
}
即,应用此办法,对明码进行加密,在业务层的时候,应用此加密的办法
@Service
@Transactional
public class UserServiceImpl implements UserService {
@Resource
private UserRepository userRepository;
@Resource
private BCryptPasswordEncoder bCryptPasswordEncoder; // 注入 bcryct 加密
@Override
public User add(User user) {user.setPassword(bCryptPasswordEncoder.encode(user.getPassword())); // 对明码进行加密
User user2 = userRepository.save(user);
return user2;
}
@Override
public ResultInfo login(User user) {ResultInfo resultInfo=new ResultInfo();
User user2 = userRepository.findByName(user.getName());
if (user2==null) {resultInfo.setCode("-1");
resultInfo.setMessage("用户名不存在");
return resultInfo;
}
// 判断明码是否正确
if (!bCryptPasswordEncoder.matches(user.getPassword(),user2.getPassword())) {resultInfo.setCode("-1");
resultInfo.setMessage("明码不正确");
return resultInfo;
}
resultInfo.setMessage("登录胜利");
return resultInfo;
}
}
即,应用 BCryptPasswordEncoder 对明码进行加密,保留数据库
应用数据库认证
这里应用数据库认证 SpringSecurity
设计数据表
这里设计数据表
着重配置 SpringConfig
@Configurable
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserService userService; // service 层注入
@Bean
PasswordEncoder passwordEncoder(){return new BCryptPasswordEncoder();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// 参数传入 Service,进行验证
auth.userDetailsService(userService);
}
@Override
protected void configure(HttpSecurity http) throws Exception {http.authorizeRequests()
.antMatchers("/admin/**").hasRole("admin")
.anyRequest().authenticated()
.and()
.formLogin()
.loginProcessingUrl("/login").permitAll()
.and()
.csrf().disable();
}
}
这里着重配置 SpringConfig
小结
着重解说了 RBAC 的权限配置,以及简略的应用 SpringSecurity,以及应用 SpringSecurity + JWT 实现前后端的拆散,以及配置 json 登录,和明码加密形式,
近期热文举荐:
1.1,000+ 道 Java 面试题及答案整顿 (2022 最新版)
2. 劲爆!Java 协程要来了。。。
3.Spring Boot 2.x 教程,太全了!
4. 别再写满屏的爆爆爆炸类了,试试装璜器模式,这才是优雅的形式!!
5.《Java 开发手册(嵩山版)》最新公布,速速下载!
感觉不错,别忘了顺手点赞 + 转发哦!