2.使用SpringSecurity进行认证和授权

认证和授权

环境搭建

  • 导入静态资源

链接:https://pan.baidu.com/s/1j1mx6k9uMfk9JWoV2-sGAA
提取码:john
复制这段内容后打开百度网盘手机App,操作更方便哦
在这里插入图片描述

  • 新建Controller,接收web端url请求
package com.boot.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @Author: JohnGea
 * @Date: 2021/5/11 13:25
 */
@Controller
public class RouterController {

    @RequestMapping({"/", "/index", "/index.html"})
    public String index() {
        return "index";
    }

    @RequestMapping("/login")
    public String login() {
        return "views/login";
    }

    @RequestMapping("/level1/{id}")
    public String level1(@PathVariable("id") String id) {
        return "views/level1/" + id;
    }

    @RequestMapping("/level2/{id}")
    public String level2(@PathVariable("id") String id) {
        return "views/level2/" + id;
    }

    @RequestMapping("/level3/{id}")
    public String level3(@PathVariable("id") String id) {
        return "views/level3/" + id;
    }
}
  • 新建一个Security配置类
package com.boot.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;

/**
 * @Author: JohnGea
 * @Date: 2021/5/12 15:04
 */
@EnableWebSecurity
public class Security extends WebSecurityConfigurerAdapter {

    //授权规则
    @Override               //http安全策略
    protected void configure(HttpSecurity http) throws Exception {
        //首页所有人可以访问,功能页只有对应的人才能访问
        //设置请求授权的一些规则~vip1只能访问level1下的所有视图、vip2只能访问level2下的所有视图...
        http.authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/level1/**").hasAnyRole("vip1")
                .antMatchers("/level2/**").hasAnyRole("vip2")
                .antMatchers("/level3/**").hasAnyRole("vip3");
        //开启登录的功能,没有权限,就要跳到登录页面
        http.formLogin();
        //开启注销功能,注销后跳到首页
        http.logout().logoutSuccessUrl("/");
    }

    //认证规则
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        /**
         * 由于这里没有连接数据库,我们从内存中取得用户名密码
         *  连接数据库的话就可以使用.jdbcAuthentication(),从数据库中获取相关的用户信息
         */
        //配置完毕后,还需要设置密码编码,不然会报错:There is no PasswordEncoder mapped for the id "null"
        //在spring security5.0+中,新增了许多加密方式,没有设置密码加密的话是不能使用的,安全检查会认为我们的密码是铭文的,不够安全
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())  //设置密码加密
                //添加一个就使用一次withUser,如果要在此添加多个,就应该使用and拼接
                .withUser("JohnGea").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1", "vip2", "vip3").and()
                .withUser("wmm").password(new BCryptPasswordEncoder().encode("123")).roles("vip1", "vip2").and()
                .withUser("welcome").password(new BCryptPasswordEncoder().encode("111")).roles("vip1");

    }
}

protected void configure(HttpSecurity http)方法中,我们规定了角色的行为:

vip1vip2vip3
只能访问level1及其以下的所有视图只能访问level2及其以下的所有视图只能访问level3及其以下的所有视图

protected void configure(AuthenticationManagerBuilder auth)方法中我们创建了三个用户,并为其分别分配了三种角色:

用户名密码角色
JohnGea123456vip1,vip2,vip3
wmm123vip1,vip2
welcome111vip1
  • index.html
    在这里插入图片描述
    在index.html,我们使用thymeleaf与spring security进行整合

需要在pom中引入以下依赖

<!--security与thymeleaf整合的依赖-->
<dependency>
   <groupId>org.thymeleaf.extras</groupId>
   <artifactId>thymeleaf-extras-springsecurity5</artifactId>
</dependency>

在index.html的<html>标签中添加以下约束

<html lang="en"
      xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/extras/spring-security"
>
  • 启动SpringBoot主程序,访问localhost:8080
    在这里插入图片描述
    在这里插入图片描述
    可以看到,不同的用户登录进来,获取到的用户角色是不一样的。
    我们使用含有vip1,vip2角色的wmm进入vip3才能进入的页面:
    在这里插入图片描述
    可以看到,页面报了一个403错误.

403错误是网站访问过程中,常见的错误提示。 资源不可用,服务器理解客户的请求,但拒绝处理它。

说明用户wmm权限不够,无法进入到只有vip3才能进入的level3页面。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值