SpringSecurity(授权认证,权限控制,注销,记住我)

前言:对于一个程序而言,安全是最重要的,并且在一个程序设计之初,就应该将其考虑到,虽然使用过滤器和拦截器也可以实现需要的功能,但是官方提供了方便开发的安全框架,知名的安全框架有SpringSecurity和Shiro。

一、SpringSecurity

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

  • WebSecurityConfigurerAdapter:自定义Security策略
  • AuthenticationManagerBuilder:自定义认证策略
  • @EnableWebSecurity:开启WebSecurity模式

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

  • “认证”(Authentication)
    身份验证是关于验证您的凭据,如用户名/用户ID和密码,以验证您的身份。
    身份验证通常通过用户名和密码完成,有时与身份验证因素结合使用。
  • “授权” (Authorization)
    授权发生在系统成功验证您的身份后,最终会授予您访问资源(如信息,文件,数据库,资金,位置,几乎任何内容)的完全权限。
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
1、授权和认证

(1)编写配置类,定义授权规则

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
     //授权
    @Override
    protected void configure(HttpSecurity http) throws Exception {
       
        //请求授权的规则
        http.authorizeRequests()
                //首页所有人可以访问,
                .antMatchers("/").permitAll()
                //不同的功能也只有对应有权限的人才能访问
                .antMatchers("/level1/**").hasAnyRole("vip1")
                .antMatchers("/level2/**").hasAnyRole("vip2")
                .antMatchers("/level3/**").hasAnyRole("vip3");
        //没有权限会自动跳到登录页面,需要开启登录页面
        http.formLogin();
    }
}

测试之后发现,无论点哪里,都会跳到登录页面。

(2)定义认证规则,并对密码进行加密

 //认证 springboot新版中密码加密后才能使用
    //对密码进行编码:PasswordEncoder
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("yao").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip3")
                .and()
                .withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3")
                .and()
                .withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");
    }
2、权限控制和注销

(1)开启自动配置的注销的功能

@Override
protected void configure(HttpSecurity http) throws Exception {
   http.csrf().disable();//关闭csrf功能
   //开启自动配置的注销的功能
   http.logout();
}

(2)前端加一个注销按钮

<a class="item" th:href="@{/logout}">
       <i class="sign-out icon"></i> 注销
</a>

(3)注销后跳转到首页

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

(4)SpringSecurity与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-springsecurity5"

增加认证判断

<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>
            角色:<span sec:authentication="principal.authorities"></span>
        </a>
    </div>
    <a class="item" th:href="@{/logout}">
        <i class="sign-out icon"></i> 注销
    </a>
</div>

不同角色显示不同内容

<!--菜单根据用户的角色动态实现-->
            <div class="column" sec:authorize="hasRole('vip1')">
                <div class="ui raised segment">
                    <div class="ui">
                        <div class="content">
                            <h5 class="content">Level 1</h5>
                            <hr>
                            <div><a th:href="@{/level1/1}"><i class="bullhorn icon"></i> Level-1-1</a></div>
                            <div><a th:href="@{/level1/2}"><i class="bullhorn icon"></i> Level-1-2</a></div>
                            <div><a th:href="@{/level1/3}"><i class="bullhorn icon"></i> Level-1-3</a></div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="column" sec:authorize="hasRole('vip2')">
                <div class="ui raised segment">
                    <div class="ui">
                        <div class="content">
                            <h5 class="content">Level 2</h5>
                            <hr>
                            <div><a th:href="@{/level2/1}"><i class="bullhorn icon"></i> Level-2-1</a></div>
                            <div><a th:href="@{/level2/2}"><i class="bullhorn icon"></i> Level-2-2</a></div>
                            <div><a th:href="@{/level2/3}"><i class="bullhorn icon"></i> Level-2-3</a></div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="column" sec:authorize="hasRole('vip3')">
                <div class="ui raised segment">
                    <div class="ui">
                        <div class="content">
                            <h5 class="content">Level 3</h5>
                            <hr>
                            <div><a th:href="@{/level3/1}"><i class="bullhorn icon"></i> Level-3-1</a></div>
                            <div><a th:href="@{/level3/2}"><i class="bullhorn icon"></i> Level-3-2</a></div>
                            <div><a th:href="@{/level3/3}"><i class="bullhorn icon"></i> Level-3-3</a></div>
                        </div>
                    </div>
                </div>
            </div>
3、记住我及首页定制

(1)开启记住我功能

//定制请求的授权规则
@Override
protected void configure(HttpSecurity http) throws Exception {
//。。。。。。。。。。。
   //记住我,采用的是系统默认的
   http.rememberMe();
}

(2)定制登录页

指定登录页

http.formLogin().loginPage("/toLogin");

在登录页加上记住我

<input type="checkbox" name="remember"> 记住我

后端接受参数并处理

//定制记住我的参数!
http.rememberMe().rememberMeParameter("remember");

完整的配置代码

package com.xupt.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
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;

import javax.sql.DataSource;

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    //授权
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        //请求授权的规则
        http.authorizeRequests()
                //首页所有人可以访问,
                .antMatchers("/").permitAll()
                //不同的功能也只有对应有权限的人才能访问
                .antMatchers("/level1/**").hasAnyRole("vip1")
                .antMatchers("/level2/**").hasAnyRole("vip2")
                .antMatchers("/level3/**").hasAnyRole("vip3");
        //定制登录页
        http.formLogin().loginPage("/toLogin");
        //开启注销功能,注销后回到首页
        http.csrf().disable(); //关闭csrf功能
        http.logout().logoutSuccessUrl("/");
        //自定义接受前端的参数
        http.rememberMe().rememberMeParameter("remember");
    }
    //认证 springboot新版中密码加密后才能使用
    //对密码进行编码:PasswordEncoder
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("yao").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip3")
                .and()
                .withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3")
                .and()
                .withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");
    }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值