25.0、springboot-springscurity用户认证和授权

25.0、springboot-springscurity用户认证和授权

简介:

        Spring Security是针对Spring项目的安全框架,也是Spring Boot底层安全模块默认的技术选型,他可以实现强大的Web安全控制,对于安全控制,我们仅需要引入spring-boot-starter-security模块,进行少量的配置,即可实现强大的安全管理!

记住几个类:

        ·WebSecurityConfigurerAdapter:自定义Security策略

        ·AuthenticationMnagerBuilder:自定义认证策略

        ·@EnableWebSecurity:开启WebSecurity模式(@Enablexxxx就是开启某个功能)

Spring Security的两个主要目标是 认证授权(访问控制)

        认证(Authentication)

        授权(Authorization)

这个概念是通用的而不是只在Spring Security中存在

第一步:要使用security首先得导入security的相关依赖:

<!--security-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

第二步:在application.properties配置文件中配置

spring.thymeleaf.cache=false

关闭模板引擎的缓存这样方便我们随时调试

第三步:搭建测试环境

1.首先在template文件夹下创建index.html文件,index中写九个链接可以分别跳转到下面创建的9个页面去。再创建一个view文件夹

2.view文件夹里创建一个login.html文件,和level1、level2、level3三个文件夹

3.分别在:

        在level1中创建1.html、2.html、3.html

        在level2中创建1.html、2.html、3.html

        在level3中创建1.html、2.html、3.html

4.在controller文件夹下创建一个RouterController.java文件

package com.hkl.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class RouterController {

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

    @RequestMapping("/gotologin")
    public String gotoLogin() {
        return "view/login";
    }

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

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

    @RequestMapping("/level3/{id}")
    public String level3(@PathVariable("id") int id) {
        return "view/level3/"+id;
    }
}

第四步:在config文件夹下创建一个配置类文件SecurityConfig.java

1.首先得继承一个叫做WebSecurityConfigurerAdapter的类

2.然后给这个类加上注解@EnableWebSecurity

3.好了做完这些我们就可以开始重写这里面的方法了:

        重写的第一个方法叫做configure(HttpSecurity http)。作用是拦截访问的url检查是否拥有相对应的权限。

        重写的第二个方法叫做configure(AuthenticationManagerBuilder auth)。作用是认证用户登录,然后授予相应的权限,这里注意需要用and来连接。这些认证的数据正常情况下应该从数据库里读取,但是由于我这里测试没有连接数据库,所以直接将数据写死。

        我会在后面总结Shiro的时候连接数据库测试

        这里注意我们的password密码如果没有加密处理的话,就会报一个PasswordEncoder的错误,

        如果在认证的方法中withUser()里写了重复的内容也会报错: Error creating bean with name 'springSecurityFilterChain' defined in class path resource

SecurityConfig.java文件如下:

package com.hkl.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
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");

        //如果我们没有开启登录页面那么我们没有相应权限然后去访问的时候就会报错
        //开启登录页面
        http.formLogin();
    }


    //认证,springboot2.1.x 可以直接使用~
    //密码加密编码处理:PasswordEncoder
    //在Spring Security 5.0+ 新增了很多的加密的方法~
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//        这些认证的数据正常情况下应该从数据库里读取,但是由于我这里测试没有连接数据库,所以直接将数据写死。
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("hkl").password(new BCryptPasswordEncoder().encode("123")).roles("vip1","vip2","vip3")
                .and()
                .withUser("root").password(new BCryptPasswordEncoder().encode("123")).roles("vip1","vip2")
                .and()
                .withUser("xiaolan").password(new BCryptPasswordEncoder().encode("123")).roles("vip1");

    }
}

然后开始测试:

进入首页后随意点击跳转链接,如果没有权限就会跳转到默认的登录界面去:

 登录后:

 点击相应的页面如果有相应的权限就会跳转过去,如果没有权限就会报错

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值