SpringBoot-搭建SpringSecurity(保姆级别)

由于篇幅有限,这里就不一一罗列了,20道常见面试题(含答案)+21条MySQL性能调优经验小编已整理成Word文档或PDF文档还有更多面试复习笔记分享如下《互联网大厂面试真题解析、进阶开发核心学习笔记、全套讲解视频、实战项目源码讲义》点击传送门即可获取!,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。**[外链图片转存中…(img-tl8OFMEN-1713309732284)][外链图片转存中…(img-p6Ujk6Kq-1713309732284)]
摘要由CSDN通过智能技术生成

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”);

// 开启自动配置的登录功能

// /login 请求来到登录页,如果没有指定默认登录界面,则会采用Security的默认登录界面

// /login?error 重定向到这里表示登录失败

http.formLogin();

}

//定义认证规则

@Override

protected void configure(AuthenticationManagerBuilder auth) throws Exception {

//在内存中定义,也可以在jdbc中去拿…

//Spring securi

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值