springboot基于角色的权限认证

Easter79
• 阅读 454

一、使用场景

springboot、springSecurity、mybatis  基于角色的权限控制

二、参考文献

https://liuyanzhao.com/7431.html

说明:网上查了一圈,只按照以上这篇博客实践成功,本文仅仅是自己实践的一些记录

三、坑

3.1

User 最好是implements UserDetails

public class User implements UserDetails {

3.2

User里角色对象要用Authority implements GrantedAuthority描述,不要用自定义的枚举或者字符串

private List authoritys;

public class Authority implements GrantedAuthority { private String id; private String username; private String role;

3.3

SecurityConfig配置使用hasRole()时,不要在前面加.anyRequest().authenticated(),在最后面可以加,加在前面会使hasRole()失效

protected void configure(HttpSecurity http) throws Exception { http.formLogin().loginPage("/login").permitAll().failureUrl("/error").and().logout().logoutSuccessUrl("/login").permitAll().and().rememberMe().alwaysRemember(true) .and().authorizeRequests() // .anyRequest().authenticated() 这行不能加在前面 .antMatchers("/").hasRole("USER") .antMatchers("/manager/**").hasRole("ROOT") .antMatchers("/user/**").hasRole("USER")   .anyRequest().authenticated() .and().csrf().disable(); }

3.4

数据库里的角色要加前缀ROLE_  例如:ROLE_ROOT

而SecurityConfig配置里要写不带前缀的例如.antMatchers("/").hasRole("ROOT")

四、解决方案

4.1 环境

jdk 8、springboot 2.0.1.RELEASE、maven、mybatis

4.2 关键依赖

<!--security-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity4</artifactId>
            <version>3.0.2.RELEASE</version>
        </dependency>

4.3 实体类

User

package com.xp.entity;

import org.apache.ibatis.annotations.Many;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class User implements UserDetails, Serializable {

    private String username;   
    private String password;  
    
    private List<Authority> authoritys; 

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }
    @Override
    public boolean isEnabled() {
        return true;
    }   

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        List<SimpleGrantedAuthority> simpleAuthorities = new ArrayList<>();
        for(GrantedAuthority authority : this.authoritys){
            simpleAuthorities.add(new SimpleGrantedAuthority(authority.getAuthority()));
        }
        return simpleAuthorities;
    } 

}

Authority 角色

public class Authority implements GrantedAuthority {
    private String id;
    private String username;
    private String role;
}

UserMapper(基于mybits注解)

可以参考:https://my.oschina.net/Cubicluo/blog/1817659

配置类

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)// 启用方法安全设置
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private DataSource dataSource;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Bean
    CustomUserService customUserService() {
        return new CustomUserService();
    }
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();      
    }
    @Bean
    public AuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
        authenticationProvider.setUserDetailsService(customUserService());
        authenticationProvider.setPasswordEncoder(passwordEncoder); // 设置密码加密方式
        return authenticationProvider;
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {        http.formLogin().loginPage("/login").permitAll().failureUrl("/error").and().logout().logoutSuccessUrl("/login").permitAll().and().rememberMe().alwaysRemember(true)
                .and().authorizeRequests()
//                .anyRequest().authenticated()  这行不能加
                .antMatchers("/").hasRole("USER")
                .antMatchers("/manager/**").hasRole("ROOT")
                .antMatchers("/user/**").hasRole("USER")
                .and().csrf().disable();
    }
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(customUserService());
        auth.authenticationProvider(authenticationProvider());
    }
}
点赞
收藏
评论区
推荐文章
kenx kenx
2年前
SpringBoot 优雅配置跨域多种方式及Spring Security跨域访问配置的坑
前言最近在做项目的时候,基于前后端分离的权限管理系统,后台使用SpringSecurity作为权限控制管理,然后在前端接口访问时候涉及到跨域,但我怎么配置跨域也没有生效,这里有一个坑,在使用SpringSecurity时候单独配置,SpringBoot跨越还不行,还需要配置Security跨域才行。什么是跨域跨域是一种浏览器同源安全策略,即浏
Wesley13 Wesley13
2年前
RBAC模型
RBAC基于角色的访问控制(RoleBasedAccessControl)作为传统访问控制(自主访问,强制访问)的有前景的代替受到广泛的关注。在RBAC中,权限与角色相关联,用户通过成为适当角色的成员而得到这些角色的权限。这就极大地简化了权限的管理。在一个组织中,角色是为了完成各种工作而创造,用户则依据它的责任和资格来被指派相应的角色,用
Wesley13 Wesley13
2年前
RBAC基于角色的权限管理
RBAC基于角色的权限管理设计篇1.1RBAC基于角色的权限管理设计篇1.0https://my.oschina.net/xiaozhutefannao/blog/1600612(https://my.oschina.net/xiaozhutefann
Stella981 Stella981
2年前
Spring Security使用详解5(角色继承)
之前的文章中,各个角色之间不具备任何关系,但一般来说角色之前是有关系的,例如ROLE\_admin一般既有admin的权限,又具有user的权限。下面介绍如何配置这种角色之间相互继承的关系。五、角色继承1、配置角色关系要配置角色继承关系,只需在SpringSecurity的配置类中提供一个RoleHierar
Stella981 Stella981
2年前
Spring Security使用详解2(基于内存的用户、URL权限配置 )
二、基于内存的用户、URL权限配置1、用户角色配置(1)我们可以通过自定义类继承WebSecurityConfigurerAdapter,从而实现对SpringSecurity更多的自定义配置。比如下面样例我们就配置了两个用户,以及他们对应的角色。注意:基于内存的用户配置在配置角色时不需要添加“ROLE\_”前缀,而
Easter79 Easter79
2年前
SpringBoot2.x搭建Eureka
1说明1.全部配置基于1.8.0_1112.当前SpringBoot使用2.0.52创建项目在SpringBoot项目生成器(https://www.oschina.net/action/GoToLink?urlhttps%3A%2F%2Fstart.spring.io%2F)中,输入Grou
Easter79 Easter79
2年前
SpringSecurity 整合SpringBoot结合jwt与rsa实现分布式认证授权
基于springsecurity整合springboot实现简单认证授权(https://www.oschina.net/action/GoToLink?urlhttps%3A%2F%2Fwww.cnblogs.com%2Fifme%2Fp%2F12184433.html)进行修改实现分布式认证,即我们常说的单点登录,简称SSO,指的是在多应用系统
Stella981 Stella981
2年前
SpringBoot2.x搭建Eureka
1说明1.全部配置基于1.8.0_1112.当前SpringBoot使用2.0.52创建项目在SpringBoot项目生成器(https://www.oschina.net/action/GoToLink?urlhttps%3A%2F%2Fstart.spring.io%2F)中,输入Grou
Stella981 Stella981
2年前
Spring Security修炼手册(四)————Security默认表达式的权限控制
       前三章主要讲的是Security对于认证的处理,那么本节,会为大家介绍基于Security默认表达式的权限控制(较为简单,无法满足复杂权限控制及多变的权限规则,后面会介绍基于自定义表达式的权限访问控制,可满足99%的业务场景的需求)。一、介绍及使用 直接进入主题,基于默认的表达式权限控制,需要在SecurityConf
Wesley13 Wesley13
2年前
C 实现基于角色的权限系统
本文demo下载地址:http://www.wisdomdd.cn/Wisdom/resource/articleDetail.htm?resourceId1068实例使用C实现基于角色的权限菜单管理系统,管理员可以添加用户,删除用户,添加分组,删除分组,添加角色,删除角色,为角色关联权限等功能,管理员用户自定义各个操作员的权限
Easter79
Easter79
Lv1
今生可爱与温柔,每一样都不能少。
文章
2.8k
粉丝
5
获赞
1.2k