Spring Security入门学习(一)-授权与认证

本文主要是对于Spring Security非常浅显的知识进行介绍,并不深入了解,只接触表面,对一些较复杂的内容也不过多描述。如文中有错误之处,望不吝赐教,谢谢~

一、Spring Security概述

spring security是 spring 项目组中用来提供安全认证服务的框架,为spring项目提供安全保障。
在web应用开发中,安全无疑是十分重要的,如果一个web应用安全得不到保障的话,那这无疑是一个失败的项目。在以往的学习中,我们可以用诸如拦截器、过滤器之类来进行安全保障,但是这样会写很多的代码,增加了工作量,所以就很有必要借助相应的框架来帮助我们完成安全保障工作(借助框架来简化拦截器、过滤器的开发复杂度),而spring security就是这样的框架。

二、Spring Security简单入门实例

(1)新建spring boot项目。

在这里插入图片描述

(2)导入素材(application.properties也要导入)。链接,提取码:1928。素材来源:【狂神说Java】SpringBoot最新教程IDEA版通俗易懂

在这里插入图片描述

(3)导入spring security依赖

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
            <version>2.2.2.RELEASE</version>
        </dependency>

(4)新建security配置类
SecurityConfig.java,注意要继承自WebSecurityConfigurerAdapter,并重写授权方法。给相应的页面设置访问权限,只有拥有该权限的用户才可访问。

package com.example.spring_security_study_demo.config;

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;

/**
 * @className: SecurityConfig
 * @description: spring security配置类
 */
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    protected void configure(HttpSecurity http) throws Exception {

        //使首页所有人都可访问
        http.authorizeRequests().antMatchers("/").permitAll();

        //level1页面只有auth1才可访问
        http.authorizeRequests().antMatchers("/level1/**").hasRole("auth1");

        //level2页面只有auth2才可访问
        http.authorizeRequests().antMatchers("/level2/**").hasRole("auth2");

        //level3页面只有auth3才可访问
        http.authorizeRequests().antMatchers("/level3/**").hasRole("auth3");
}

(5)新建控制器
注意素材里面有关登录是“toLogin”,而本程序是“login”,可自行修改。

package com.example.spring_security_study_demo.controller;

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

/**
 * @className: RouterController
 * @description: 访问控制器
 */
@Controller
public class RouterController {


    /**
     * 访问首页 index.html
     * @return
     */
    @RequestMapping({"/","/index"})
    public String index(){

        return "index";
    }

    /**
     * 访问登录页
     * @return
     */
    @RequestMapping("/login")
    public String login(){

        return "views/login";
    }

    /**
     * 访问views/level1/下的页面
     * @param id
     * @return
     */
    @RequestMapping("/level1/{id}")
    public String level1(@PathVariable("id") Integer id){

        return "views/level1/"+id;

    }

    /**
     * 访问views/level2/下的页面
     * @param id
     * @return
     */
    @RequestMapping("/level2/{id}")
    public String level2(@PathVariable("id") Integer id){

        return "views/level2/"+id;

    }

    /**
     * 访问views/level3/下的页面
     * @param id
     * @return
     */
    @RequestMapping("/level3/{id}")
    public String level3(@PathVariable("id") Integer id){

        return "views/level3/"+id;

    }
}

(6)启动项目,运行成功后,在浏览器中输入

http://localhost:8080/

即可看到如下页面
在这里插入图片描述

再点击Level1-1-1,可看到如下页面:
在这里插入图片描述
可发现首页都可访问,而level1/1/1页面不能被访问(权限不足),这说明我们前面的security配置成功,赋予了不同页面的访问权限。

(7)在security配置类(SecurityConfig.java)中,重写认证方法,以给相应的用户认证权限。(注意本来用户的信息应该从数据库中读入,这里为方便演示,便直接给出数据)。

/**
     * 认证
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //认证 给用户授予权限
        //用 and()连接多个用户
        //用BCryptPasswordEncoder对密码进行加密
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("a").password(new BCryptPasswordEncoder().encode("123")).roles("auth1")
                .and()
                .withUser("b").password(new BCryptPasswordEncoder().encode("123")).roles("auth2")
                .and()
                .withUser("c").password(new BCryptPasswordEncoder().encode("123")).roles("auth3");
    }

(8)再启动项目,运行成功后,在浏览器中输入

http://localhost:8080/login

进入登录页面,输入相应的信息(以用户a为例,用户名为a,密码为123)
再点击Level1-1-1,可看到如下页面:
在这里插入图片描述
此时用户a可访问Level1-1-1页面,并且其他用户(b和c)是不能访问的。

三、总结

spring security是 spring 项目组中用来提供安全认证服务的框架,可以很浅显地理解为借助spring security可以简化编写拦截器和过滤器的工作。
使用spring security:

  • 引入spring-boot-starter-security依赖
  • 编写相应的配置类并继承自WebSecurityConfigurerAdapter,再重写相关函数

在这里插入图片描述
2020.04.18

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值