SpringSecurity之自定义认证规则

1. 创建Springboot项目,引入SpringSecurity依赖:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
2. 为了方便,替换SpringSecurity默认的用户名和生成的密码,使用自定义账号密码:
# 设置账号为 root
spring.security.user.name=root
# 设置密码为 root
spring.security.user.password=root
3. 创建两个Controller,一个可以放行,一个会被拦截

这里 “/index” 作为 公共资源,可以访问,“/hello” 为 受限资源,不可以访问。

IndexController:

/**
 * 该类映射的网址是公共资源,不受security保护,任何人都可以访问
 */
@RestController
public class IndexController {
    @RequestMapping("/index")
    public String index() {
        return "hello index";
    }

}

HelloController:

/**
 * 该类是私有资源,需要进行认证授权后才可以访问
 */
@RestController
public class HelloController {
    @RequestMapping("/hello")
    public String hello() {
        return "hello spring security";
    }

}
4. 创建一个类,继承 WebSecurityConfigurerAdapter 类,继承这个类后,就可以在 configure(HttpSecurity http) 方法中自定义认证规则了。
package com.example.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
public class MyWebSecurityConfigurer extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()        // 开启请求的权限管理
                .mvcMatchers("/index").permitAll()      // 放行 "/index" 请求
				//.mvcMatchers("/hello").authenticated()       指定 "/hello" 请求需要认证
                .anyRequest().authenticated()       // 除了放行的请求,所有请求都需要认证
                .and()
                .formLogin()        // 进行表单认证
                //.loginPage("");       // 更换登录界面
//      http.formLogin();        也可以单独写表单认证,不过更建议链式调用
    }
}

注意:

  1. 先放行,后认证
  2. 注意 @Configuration 注解,声明该类是一个配置类。
5. 效果

访问 “/index” 可以正常访问:
在这里插入图片描述
而访问 “/hello” 则会跳转到 SpringSecurity 自带的登录页面:

在这里插入图片描述
输入自定义密码后可以正常访问:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值