Spring Security用户认证和权限控制

Spring Security用户认证和权限控制

1.介绍

spring security 的核心功能主要包括:

认证 (你是谁)
授权 (你能干什么)
攻击防护 (防止伪造身份)

实际应用系统中,为了安全起见,一般都必备用户认证(登录)和权限控制的功能,以识别用户是否合法,以及根据权限来控制用户是否能够执行某项操作。
Spring Security是一个安全相关的框架,能够与Spring项目无缝整合,本文主要是介绍Spring Security默认的用户认证和权限控制的使用方法和原理

2.数据库表设计

在这里插入图片描述
设计5张表:
user (用户表)
role (角色表)
role_user (用户角色关联表)
jurisdiction (权限表)
role_jurisdiction (角色权限关联表)

每个用户都对应一种角色,但一种角色可以有多个权限

3.示例

3.1. 首先创建一个SpringBoot项目

3.2. 配置说明
我们界面使用Thymeleaf模板
pom.xml引入SpringSecurity、thymeleaf 依赖

<!-- thymeleaf -->
       <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-thymeleaf</artifactId>
       </dependency>
<!-- security -->
       <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-security</artifactId>
       </dependency>

application.properties
记得修改成你自己的配置

#thymeleaf配置
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.check-template-location=true
spring.thymeleaf.suffix=.html
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.servlet.content-type=text/html
spring.thymeleaf.mode=HTML
spring.thymeleaf.cache=false

#数据源配置
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url = jdbc:mysql://localhost:3306/security?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=root

#映射文件
mybatis.mapper-locations=classpath:
#实体类起别名
mybatis.type-aliases-package=
#打印语句sql
logging.level.com.lyh.dao=debug

3.3. 创建配置类
配置类需要继承WebSecurityConfigurerAdapter类
重写里面的
configure(HttpSecurity http)、configure(AuthenticationManagerBuilder auth)方法
配置需要认证的url,这里除了登录,其他都需要进行认证
需要使用@EnableWebSecurit启用Security

@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
   

    @Autowired
    private UserDetailsService userDetailsServiceImpl;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
   
        // 定制请求的授权规则
        http.authorizeRequests()
                 //antMatchers("/add")存放的是请求路径
                .antMatchers("/").permitAll()// 首页所有人可以访问
                .antMatchers("/add").hasAuthority("ADD")//需要ADD权限才能访问
                .antMatchers("/del").hasAuthority("DEL")//需要DEL权限才能访问
                .antMatchers("/upd").hasAuthority("UPD")//需要UPD权限才能访问
                .antMatchers("/list").hasAuthority("LIST")//需要LIST权限才能访问
                .antMatchers("/**")
                .fullyAuthenticated()//所有请求都必须登录
                .and()
                .formLogin()//使用默认的登录表单
                .and()
                .logout().permitAll();//注销
    }
    /**
     * 用户认证配置
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
   
        auth
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Spring Security身份认证权限控制代码可以通过配置文件或者Java代码实现。其中,配置文件方式需要在Spring配置文件中添加如下代码: ``` <security:http auto-config="true" use-expressions="true"> <security:intercept-url pattern="/admin/**" access="hasRole('ROLE_ADMIN')" /> <security:intercept-url pattern="/user/**" access="hasRole('ROLE_USER')" /> <security:form-login login-page="/login" default-target-url="/home" authentication-failure-url="/login?error" /> <security:logout logout-success-url="/login?logout" /> </security:http> <security:authentication-manager> <security:authentication-provider> <security:user-service> <security:user name="admin" password="admin" authorities="ROLE_ADMIN" /> <security:user name="user" password="user" authorities="ROLE_USER" /> </security:user-service> </security:authentication-provider> </security:authentication-manager> ``` 在Java代码中,可以通过继承WebSecurityConfigurerAdapter类来实现身份认证权限控制,示例代码如下: ``` @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("admin").password("admin").roles("ADMIN") .and() .withUser("user").password("user").roles("USER"); } @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/admin/**").hasRole("ADMIN") .antMatchers("/user/**").hasRole("USER") .and() .formLogin() .loginPage("/login") .defaultSuccessUrl("/home") .failureUrl("/login?error") .and() .logout() .logoutSuccessUrl("/login?logout"); } } ``` 以上是Spring Security身份认证权限控制的代码示例。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值