SpringSecurity安全框架

91 阅读2分钟

SpringSecurity也是Spring框架中的一员,他可以很好的跟SpringBoot合作,主要用来对用户登录的认证和授权。所谓认证也就是哪些用户可以登录,登录之后扮演哪些角色,在同一个用户下扮演不同的角色(不管扮演哪种角色,该用户还是该用户),例如在root用户下,可以有vip1、vip2和vip3三个角色,当然也可以在hzy用户下有vip1这一个角色,都可以自定义。 所谓授权,也就是控制不同的角色可以访问不同的内容,例如我们想要vip1可以访问level1下的内容,vip2可以访问level2下的内容,vip3可以访问level3下的内容,所以我们的root用户就可以访问level1、level2和level3下的内容,因为他扮演着这三种角色,而hzy只能访问level1下的内容,因为他只扮演了vip1这一个角色(跟现实中的我们很像,我们在不同的场合扮演着不同的角色,但是不管扮演哪种角色,我还是我!)

对上面的描述,我们给出对应的配置类

package com.hzy.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 {

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

    }

    // 授权
    @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()
                .usernameParameter("username")
                .passwordParameter("password")
                .loginPage("/toLogin");

        // 开启注销功能,跳到首页
        http.logout().logoutSuccessUrl("/");
        // 开启记住我功能,自定义接受前端参数
        http.rememberMe().rememberMeParameter("remember");

    }
}

之所以对密码进行了加密是因为不加密会报下面这个错

在上面的配置类中,授权的时候,对登录和登出进行了操作,对登录进行了账号和密码的获取以及页面的指定跳转,对登出进行了页面的指定跳转,前端核心代码如下

<div class="right menu">
                <!--未登录-->
                <a class="item" th:href="@{/toLogin}">
                    <i class="address card icon"></i> 登录
                </a>
                <!--注销-->
                <a class="item" th:href="@{/logout}">
                    <i class="sign-out icon"></i> 注销
                </a>
            </div>

另外在授权配置类中,还对登录页面的记住我进行了操作,其核心前端代码如下

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