SpringSecurity学习笔记

点击下载源码

SpringSecurity

  • 1.环境搭建
    • 1.1项目创建
    • 1.2 创建Controller
  • 2.用户认证与授权
    • 2.1 SecurityConfig
  • 3.注销与权限控制
    • 3.1SecurityConfig 接上面的程序
    • 3.2导入依赖
    • 3.3index.html 首页

1.环境搭建

1.1项目创建

SpringSecurity学习笔记_第1张图片
SpringSecurity学习笔记_第2张图片
目录结构
SpringSecurity学习笔记_第3张图片
添加thymeleaf依赖

<dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-thymeleafartifactId>
dependency>

1.2 创建Controller

package com.tamy.controller;

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

@Controller
public class SecurityController {
//    要记得添加Thymeleaf依赖,不然就会报错,Path[/index]
    @RequestMapping({"/","/index"})
    public String index(){
        return "index";
    }

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

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

    @RequestMapping("logout")
    public String logout(){
        return "logout";
    }
}

2.用户认证与授权

2.1 SecurityConfig

package com.tamy.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();
    }

//    密码编码
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //这些数据应该从数据库中读取
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("user").password(new BCryptPasswordEncoder().encode("123")).roles("vip1","vip2")
                .and()
                .withUser("admin").password(new BCryptPasswordEncoder().encode("123")).roles("vip1","vip2","vip3");
    }
}

3.注销与权限控制

3.1SecurityConfig 接上面的程序

package com.tamy.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().loginPage("/login");

        http.logout().logoutSuccessUrl("/");

        //防止网站攻击:post   get
        http.csrf().disable();  //关闭csrf功能,注销失败存在的原因,默认是开启的

		//记住我功能
        //firefox失败,不能成功保存cookie,关闭浏览器,cookie自动删除
        http.rememberMe().rememberMeParameter("remember");
    }

//    密码编码

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //这些数据应该从数据库中读取,现在是在内存中模拟账号
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("user").password(new BCryptPasswordEncoder().encode("123")).roles("vip1","vip2")
                .and()
                .withUser("admin").password(new BCryptPasswordEncoder().encode("123")).roles("vip1","vip2","vip3");
    }
}

3.2导入依赖

<dependency>
            <groupId>org.thymeleaf.extrasgroupId>
            <artifactId>thymeleaf-extras-springsecurity5artifactId>
            <version>3.0.4.RELEASEversion>
dependency>

3.3index.html 首页


<html lang="en"
      xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity5">


<head>
    <meta charset="UTF-8">
    <title>Titletitle>
head>

<body>
    <h1>SpringSecurityh1>

    <div sec:authorize="!isAuthenticated()">
        <a th:href="@{/login}">登录a>
    div>

    <div sec:authorize="isAuthenticated()">
        <a th:href="@{/logout}">注销a>
    div>
    <hr>

	
    <div sec:authorize="hasRole('vip1')">
        <span>vip1span>
        <a href="/level1/1">vip1.htmla>
    div>
    <hr>
    
    <div sec:authorize="hasRole('vip2')">
        <span>vip2span>
        <a href="/level2/1">vip2.htmla>
    div>
    <hr>
    
    <div sec:authorize="hasRole('vip3')">
        <span>vip3span>
        <a href="/level3/1">vip3.htmla>
    div>
    <hr>
body>
html>

你可能感兴趣的:(Java)