SpringSecurity

时间:2020-07-12
本文章向大家介绍SpringSecurity,主要包括SpringSecurity使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

Spring Security(安全)

不是功能性需求

设计之初考虑

框架:shiro、Spring Security,功能类似

认证,授权

  • 功能权限
  • 访问权限
  • 菜单权限
  • ...拦截器,过滤器:大量源生代码

MVC - SPRING - BOOT - 框架思想

导入thymeleaf依赖

		<dependency>
			<groupId>org.thymeleaf</groupId>
			<artifactId>thymeleaf-spring5</artifactId>
			<version>3.0.11.RELEASE</version>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>org.thymeleaf.extras</groupId>
			<artifactId>thymeleaf-extras-java8time</artifactId>
			<version>3.0.4.RELEASE</version>
			<scope>compile</scope>
		</dependency>

com.peng.controller.RouterController.java 搭建环境

package com.peng.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("toLogin")
    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;
    }
}

谁都能看见的界面,明显不合理

AOP:切面编程

整合 Spring Security

记住几个类:

  • WebSecurityConfigurerAdapter: 自定义Security策略
  • AuthenticationManagerBuilder: 自定义认证策略
  • @EnableWebSecurity: 开启WebSecurity模式 ,@Enablexxxx 开启某个功能

Spring Security的两个主要目标是“认证"和"授权”(访问控制)
“认证”(Authentication)
"授权”(Authorization)
这个概念是通用的,而不是只在Spring Security中存在。

导入依赖

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

com.peng.config.SecurityConfig.java 横向添加认证和授权

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;

//AOP : 拦截器!
@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");

        //没有权限默认跳到登录页面,需要开启登录页面
        // 为什么能进入 /login !
        http.formLogin().loginPage("/toLogin").loginProcessingUrl("/login"); //走定制的登录页

        //防止网站攻击 get post
        http.csrf().disable(); //关闭csrf功能

        //注销,跳回首页
        http.logout().logoutSuccessUrl("/");

        //开启记住我功能 cookie 默认保存两周
        http.rememberMe();
    }

    //认证
    //密码编码:PasswordEncoder
    //在Spring Security 5.0+ 新增了很多的加密方法
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        //这些数据正常应该从数据库中读取
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("peng").password(new BCryptPasswordEncoder().encode("123")).roles("vip2","vip3")
                .and().withUser("root").password(new BCryptPasswordEncoder().encode("123")).roles("vip1","vip2","vip3")
                .and().withUser("guest").password(new BCryptPasswordEncoder().encode("123")).roles("vip1");

        /*数据库中读取
        auth.jdbcAuthentication()
                .dataSource(datadataSource)
                .withDefaultSchema()
                .withUser(users.username("peng").password("123").roles("vip2"))
                ...........;
                */
    }
}

thymeleaf 里控制安全,先导包

		<!--security-thymeleaf整合包-->
		<dependency>
			<groupId>org.thymeleaf.extras</groupId>
			<artifactId>thymeleaf-extras-springsecurity4</artifactId>
			<version>3.0.4.RELEASE</version>
		</dependency>

导入命名空间

xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4"

动态显示 登陆 和 注销

<!--登录注销-->
<div class="right menu">
    <!--如果未登录,显示登录界面-->
    <div sec:authorize="!isAuthenticated()">
        <a class="item" th:href="@{/toLogin}">
            <i class="address card icon"></i> 登录
        </a>
    </div>

    <!--如果登录:用户名,注销-->
    <div sec:authorize="isAuthenticated()">
        <a class="item">
            用户名:<span sec:authentication="name"></span>
        </a>
    </div>
    <div sec:authorize="isAuthenticated()">
        <a class="item" th:href="@{/logout}">
            <i class="sign-out icon"></i> 注销
        </a>
    </div>

</div>

动态显示菜单

<div class="column" sec:authorize="hasRole('vip1')">
    <div ............/></div>
<div class="column" sec:authorize="hasRole('vip2')">
	<div ............/></div>
<div class="column" sec:authorize="hasRole('vip3')">
    <div ............/></div>

原文地址:https://www.cnblogs.com/peng8098/p/java_26.html