SpringBoot-搭建SpringSecurity(保姆级别)

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 security 5.0中新增了多种加密方式,

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值