SpringBoot-搭建SpringSecurity(保姆级别)

本文介绍了如何在SpringBoot应用中集成SpringSecurity,通过配置WebSecurityConfigurerAdapter实现不同URL的权限控制,包括登录、注销、记住我功能,并自定义登录界面。详细步骤包括导入依赖、配置安全规则、内存中定义用户角色、开启自动登录等功能。
摘要由CSDN通过智能技术生成

《一线大厂Java面试题解析+核心总结学习笔记+最新讲解视频+实战项目源码》点击传送门,即可获取!

public String toLogin(){

return “views/login”;

}

@RequestMapping(“/level1/{id}”)

public String level1(@PathVariable(“id”) int id){

return “views/level1/”+id;

}

@RequestMapping(“/level2/{id}”)

public String level2(@PathVariable(“id”) int id){

return “views/level2/”+id;

}

@RequestMapping(“/level3/{id}”)

public String level3(@PathVariable(“id”) int id){

return “views/level3/”+id;

}

}

4.测试以上步骤是否成功

启动项目

首页:

登录页:

成功!

但我们目前是可以任意对level1~level3进行随意访问的,接着我们要做的就是只有相应权限的人才可以进行访问

3. 增加上认证和授权的功能

==============

(1)导入Security依赖:

org.springframework.boot

spring-boot-starter-security

(2)编写 Spring Security 配置类

重写WebSecurityConfigurerAdapter的两个配置方法:

configure(HttpSecurity http):定制请求的授权规则

configure(AuthenticationManagerBuilder auth):定义认证规则

package com.yixin.demo.config;

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;

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;

@EnableWebSecurity// 开启WebSecurity模式

public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Override

protected void configure(HttpSecurity http) throws Exception {

// 首页所有人都可以访问,功能也只有对应有权限的人才能访问到

// 请求授权的规则

http.authorizeRequests()

.antMatchers(“/”).permitAll()

.antMatchers(“/level1/**”).hasRole(“vip1”)

.antMatchers(“/level2/**”).hasRole(“vip2”)

.antMatchers(“/level3/**”).hasRole(“vip3”);

  • 28
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值