SpringBoot——安全框架SpringSecurity

SpringSecurity是撒子?

SpringSecurity是针对Spring项目的安全框架,是身份认证和访问控制(授权)的一个框架。之前我们都是使用拦截器来实现,但是大量的原生代码,太繁琐,所以就有了SpringSecurity。

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

 

用户认证和授权

我们可以用这个安全框架来完成授权就是给用户,比如说普通游客的人只能看到网站功能的一部分,而管理员别普通用户的功能更多一些;认证就是根据用户的登录信息来判断用户的权限。

首先导入SpringSecurity依赖:

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

用户认证和授权:

package com.lyr.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.builders.WebSecurity;
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");

        //没有权限就会到登陆页面
        //.usernameParameter("") // 前端用户名和后端不一致
	    //.passwordParameter("")
        //http.formLogin();
        http.formLogin().loginPage("/toLogin");

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

        //开启注销功能
        http.logout();

        //开启记住我功能,有效期14天
        //http.rememberMe();
        http.rememberMe().rememberMeParameter("remember");
    }

    //认证
    //密码编码:
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //auth.jdbcAuthentication()  从数据库中取

        //auth.inMemoryAuthentication()从内存中取
        //.passwordEncoder(new BCryptPasswordEncoder())  加密
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("guest").password(new BCryptPasswordEncoder().encode("111111")).roles("vip1")
                .and()
                .withUser("lyr").password(new BCryptPasswordEncoder().encode("111111")).roles("vip1","vip2")
                .and()
                .withUser("root").password(new BCryptPasswordEncoder().encode("111111")).roles("vip1","vip2","vip3");

    }
}

权限控制

vip1的人只能看到相对应level1下的内容,vip2的人可以看到相对应level1、2下的内容,vip3的人可以看到相对应level1、2、3下的内容,没有登陆的游客只能访问首页。

需要用到Thymeleaf和SpringSecurity整合,所以要导入整合的依赖。

<!--springSecurity-thymeleaf-->
        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity5</artifactId>
            <version>3.0.4.RELEASE</version>
        </dependency>

登陆、注销权限:

<!--登录注销-->
            <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>

访问权限:

在前端使用springsecurity时需要先导入命名空间

xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity5"
<div 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>

效果:

没登陆时

登陆游客权限,游客只能访问到level1的内容。

发布了322 篇原创文章 · 获赞 61 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/wan_ide/article/details/105167734