Spring Boot Security(一)

Spring Security 配置

参考 https://docs.spring.io/spring-security/site/docs/5.4.1/guides/#hello-world

1、首先在 pom.xml 文件中添加 Spring Security

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

2、编写配置文件

package com.wkw.bms.test.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
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.password.PasswordEncoder;

/**
 * @author : Administrator
 * @project : BMS
 * @date : 2020/10/20 21:37
 **/

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter
{
    /**
     * 登录表单用户名 name 和密码 name 属性名
     */
    private String USER_NAME_ATTRIBUTE = "username";
    private String USER_PASSWORD_ATTRIBUTE = "password";
    /**
     * 规则定义
     */
    private String USER_ROLE = "USER";
    private String ADMIN_ROLE = "ADMIN";

    /**
     * 定义授权规则
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure (HttpSecurity http)
    throws Exception
    {
        // 认证配置
        http.authorizeRequests()
                // 登录页面无需权限
                .antMatchers("/login","/error","/about").permitAll()
                // 过滤掉静态文件
                .antMatchers("/css/**","/data/**","/fonts/**","/icons-reference/**","/img/**","/js/**","/vendor/**").permitAll()
                // 其他页面都需登录访问
                .antMatchers("/**").hasRole(USER_ROLE)
                // 系统管理员页面需管理员权限
                .antMatchers("/sys/**").hasRole(ADMIN_ROLE)
                .anyRequest()
                .authenticated();
        //登录配置
        http.formLogin()
                // 自定义的登录页
                .loginPage("/login")
                // 处理登录请求的 url,和 login.html 中 表单中 action 一致,SpringBoot 将自动进行认证,认证成功之后将请求发送给 successForwardUrl 处理
                .loginProcessingUrl("/login-check")
                .usernameParameter(USER_NAME_ATTRIBUTE)
                .passwordParameter(USER_PASSWORD_ATTRIBUTE)
                // 且 successForwardUrl 必须接受 POST 请求
                .successForwardUrl("/login-check")
                .permitAll()
                .and()
                .rememberMe();


        // 登出配置
        http.logout()
                .logoutUrl("/logout")
                .invalidateHttpSession(true)
                .logoutSuccessUrl("/login")
                .permitAll()
                .and()
                .csrf()
                .disable();

    }

    /**
     * 定义认证规则
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure (AuthenticationManagerBuilder auth)
    throws Exception
    {
        //super.configure(auth);
        auth.inMemoryAuthentication()
                .withUser("zolmk").password("zolmk").roles(USER_ROLE,ADMIN_ROLE);
    }

    @Bean
    public PasswordEncoder passwordEncoder()
    {
        return new com.wkw.bms.test.config.PasswordEncoder();
    }
}

3、对应的 Controller

package com.wkw.bms.controller;

import org.springframework.beans.factory.annotation.Autowired;
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.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author : Administrator
 * @project : BMS
 * @date : 2020/10/25 19:02
 **/

@Controller
@RequestMapping("/")
public class BaseController
{
    @RequestMapping(value = {"/login","/login.html"},method = RequestMethod.GET)
    public String login()
    {
        return "login";
    }
    @RequestMapping(value = {"/login-check"},method = RequestMethod.POST)
    public String loginCheck(HttpServletRequest request,HttpServletResponse response)
    {
        // 在这里传一些信息
        return "redirect:index.html";
    }

    @RequestMapping(value = {"/index","/index.html","/main.html","/"},method = RequestMethod.GET)
    public String index()
    {
        return "index";
    }

    @RequestMapping(value = {"/charts","/charts.html"},method = RequestMethod.GET)
    public String charts()
    {
        return "charts";
    }

    @RequestMapping(value = {"/forms","/forms.html"},method = RequestMethod.GET)
    public String forms()
    {
        return "forms";
    }

    @RequestMapping(value = {"/register","/register.html"},method = RequestMethod.GET)
    public String register()
    {
        return "register";
    }
    @RequestMapping(value = {"/tables","/tables.html"},method = RequestMethod.GET)
    public String tables()
    {
        return "tables";
    }


}

4、对应的 PasswordEncoder(自己定制)

package com.wkw.bms.test.config;

/**
 * @author : Administrator
 * @project : BMS
 * @date : 2020/10/24 22:04
 **/

public class PasswordEncoder implements org.springframework.security.crypto.password.PasswordEncoder
{

    @Override
    public String encode (CharSequence rawPassword)
    {
        return rawPassword.toString();
    }

    @Override
    public boolean matches (CharSequence rawPassword, String encodedPassword)
    {
        return rawPassword.toString().equals(encodedPassword);
    }
}

posted @ 2020-12-02 15:47  zolmk  阅读(83)  评论(0编辑  收藏  举报