1. 程式人生 > >SpringBoot整合Spring Security(1)——入門程式

SpringBoot整合Spring Security(1)——入門程式

因為專案需要,第一次接觸Spring Security,早就聽聞Spring Security強大但上手困難,今天學習了一天,翻遍了全網資料,才僅僅出入門道,特整理這篇文章來讓後來者少踩一點坑(本文附帶例項程式,請放心食用

本篇文章環境:SpringBoot 2.0 + Mybatis + Spring Security 5.0

原始碼地址:https://github.com/wzy010/home.git

專案結構圖如下:

建立springboot專案

選擇mybatis和mysql

文章目錄

Step1 匯入依賴

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

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

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

        <!-- https://mvnrepository.com/artifact/javax.persistence/persistence-api -->
        <dependency>
            <groupId>javax.persistence</groupId>
            <artifactId>persistence-api</artifactId>
            <version>1.0</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.14</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.1</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

    </dependencies>

Step2 建立資料庫

一般許可權控制有三層,即:使用者<–>角色<–>許可權,使用者與角色是多對多,角色和許可權也是多對多。這裡我們先暫時不考慮許可權,只考慮使用者<–>角色

建立使用者表sys_user

CREATE TABLE `sys_user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `password` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

建立許可權表sys_role

CREATE TABLE `sys_role` (
  `id` int(11) NOT NULL,
  `name` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

建立使用者-角色表sys_user_role

CREATE TABLE `sys_user_role` (
  `user_id` int(11) NOT NULL,
  `role_id` int(11) NOT NULL,
  PRIMARY KEY (`user_id`,`role_id`),
  KEY `fk_role_id` (`role_id`),
  CONSTRAINT `fk_role_id` FOREIGN KEY (`role_id`) REFERENCES `sys_role` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `fk_user_id` FOREIGN KEY (`user_id`) REFERENCES `sys_user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

初始化一下資料:

INSERT INTO `sys_role` VALUES ('1', 'ROLE_ADMIN');
INSERT INTO `sys_role` VALUES ('2', 'ROLE_USER');

INSERT INTO `sys_user` VALUES ('1', 'admin', '123');
INSERT INTO `sys_user` VALUES ('2', 'wzy', '123');

INSERT INTO `sys_user_role` VALUES ('1', '1');
INSERT INTO `sys_user_role` VALUES ('2', '2');

博主有話說:

這裡的許可權格式為ROLE_XXX,是Spring Security規定的,不要亂起名字哦。

Step3 準備頁面

靜態資源放在resource的static目錄下

因為是示例程式,頁面越簡單越好,只用於登陸的login.html以及用於登陸成功後的home.html

login.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登陸</title>
</head>
<body>
<h1>登陸</h1>
<form method="post" action="/login">
    <div>
        使用者名稱:<input type="text" name="username">
    </div>
    <div>
        密碼:<input type="password" name="password">
    </div>
    <div>
        <button type="submit">立即登陸</button>
    </div>
</form>
</body>
</html>

博主有話說:

使用者的登陸認證是由Spring Security進行處理的,請求路徑預設為/login,使用者名稱預設為username,密碼預設為password

home.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>登陸成功</h1>
    <a href="/admin">檢測ROLE_ADMIN角色</a>
    <a href="/user">檢測ROLE_USER角色</a>
    <button onclick="window.location.href='/logout'">退出登入</button>
</body>
</html>

Step4 配置application.properties

在配置檔案中配置下資料庫連線:

spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/security?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=GMT
spring.datasource.username=root
spring.datasource.password=root

#開啟Mybatis下劃線命名轉駝峰命名
mybatis.configuration.map-underscore-to-camel-case=true

Step5 建立實體、Dao、Service和Controller

5.1 實體

(1)SysUser

package com.chwx.springbootspringsecurity.pojo;


import lombok.Data;

import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.Table;
import java.io.Serializable;

@Data
@Table(name="sys_user")
public class SysUser implements Serializable {

    @Id
    private Integer id;
    private String name;
    private String password;
}

(2)SysRole

package com.chwx.springbootspringsecurity.pojo;

import lombok.Data;

import javax.persistence.Id;
import javax.persistence.Table;
import java.io.Serializable;
@Data
@Table(name="sys_role")
public class SysRole implements Serializable {
    @Id
    private Integer id;
    private String name;
}

(3)SysUserRole

package com.chwx.springbootspringsecurity.pojo;

import lombok.Data;

import javax.persistence.Column;
import javax.persistence.Table;
import java.io.Serializable;

@Data
@Table(name="sys_user_role")
public class SysUserRole implements Serializable {
    @Column(name="user_id")
    private  Integer userId;
    @Column(name="role_id")
    private Integer roleId;
}

5.2 Dao

(1)SysUserMapper

package com.chwx.springbootspringsecurity.dao;

import com.chwx.springbootspringsecurity.pojo.SysUser;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

@Mapper
public interface SysUserMapper {
    @Select("select * from sys_user where id = #{id}")
    SysUser selectById(Integer id);
    @Select("select * from sys_user where name = #{name}")
    SysUser selectByName(String name);

}

(2)SysRoleMapper

package com.chwx.springbootspringsecurity.dao;

import com.chwx.springbootspringsecurity.pojo.SysRole;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

@Mapper
public interface SysRoleMapper {
    @Select("select * from sys_role where id =#{id}")
    SysRole selectById(Integer id);
}

(3)SysUserRoleMapper

package com.chwx.springbootspringsecurity.dao;

import com.chwx.springbootspringsecurity.pojo.SysUserRole;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

import java.util.List;

@Mapper
public interface SysUserRoleMapper {
    @Select("select * from sys_user_role where user_id = #{userId}")
    List<SysUserRole> listByUserId(Integer userId);
}

5.3 Service

(1)SysUserService

package com.chwx.springbootspringsecurity.service;

import com.chwx.springbootspringsecurity.dao.SysUserMapper;
import com.chwx.springbootspringsecurity.pojo.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    public SysUser selectById(Integer id){
        return  sysUserMapper.selectById(id);
    }

    public SysUser selectByName(String name){
        return sysUserMapper.selectByName(name);
    }
}

(2)SysRoleService

package com.chwx.springbootspringsecurity.service;

import com.chwx.springbootspringsecurity.dao.SysRoleMapper;
import com.chwx.springbootspringsecurity.pojo.SysRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class SysRoleService {
    @Autowired
    private SysRoleMapper sysRoleMapper;

    public SysRole selectById(Integer id){
        return sysRoleMapper.selectById(id);
    }
}

(3)SysUserRoleService

package com.chwx.springbootspringsecurity.service;

import com.chwx.springbootspringsecurity.dao.SysUserRoleMapper;
import com.chwx.springbootspringsecurity.pojo.SysUserRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SysUserRoleService {
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    public List<SysUserRole> listByUserId(Integer userId){
        return  sysUserRoleMapper.listByUserId(userId);
    }
}

5.4 Controller

package com.chwx.springbootspringsecurity.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class LoginController {

    private Logger logger = LoggerFactory.getLogger(LoginController.class);

    @RequestMapping("/")
    public String showHome(){
        String name = SecurityContextHolder.getContext().getAuthentication().getName();
        logger.info("當前登入使用者: "+name);
        return "home.html";
    }

    @RequestMapping("/login")
    public String showLogin(){
        return "login.html";
    }

    @RequestMapping("/admin")
    @ResponseBody
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    public String printAdmin(){
        return "如果你看見這句話,說明你有ROLE_ADMIN角色";
    }

    @RequestMapping("/user")
    @ResponseBody
    @PreAuthorize("hasRole('ROLE_USER')")
    public String printUser(){
        return "如果你看見這句話,說明你有ROLE_USER角色";
    }

}

博主有話說:

  • 如程式碼所示,獲取當前登入使用者:SecurityContextHolder.getContext().getAuthentication()
  • @PreAuthorize用於判斷使用者是否有指定許可權,沒有就不能訪問

Step6 配置SpringSecurity

6.1 UserDetailsService

首先我們需要自定義UserDetailsService,將使用者資訊和許可權注入進來。

我們需要重寫loadUserByUsername方法,引數是使用者輸入的使用者名稱。

返回值是UserDetails,這是一個介面,一般使用它的子類org.springframework.security.core.userdetails.User(當前你也可以自定義個UserDetails),它有三個引數,分別是使用者名稱、密碼和許可權集。
 

package com.chwx.springbootspringsecurity.common;

import com.chwx.springbootspringsecurity.pojo.SysRole;
import com.chwx.springbootspringsecurity.pojo.SysUser;
import com.chwx.springbootspringsecurity.pojo.SysUserRole;
import com.chwx.springbootspringsecurity.service.SysRoleService;
import com.chwx.springbootspringsecurity.service.SysUserRoleService;
import com.chwx.springbootspringsecurity.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Service
public class CustomUserDetailsService implements UserDetailsService {
    @Autowired
    private SysUserService userService;
    @Autowired
    private SysRoleService roleService;
    @Autowired
    private SysUserRoleService userRoleService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Collection<GrantedAuthority> authorities = new ArrayList<>();
        //資料庫獲取使用者資訊
        SysUser user = userService.selectByName(username);
        //判斷使用者是否存在
        if (user == null){
            System.out.println("使用者不存在");
            throw new UsernameNotFoundException("使用者不存在");
        }

        //新增許可權
        List<SysUserRole> userRoles = userRoleService.listByUserId(user.getId());
        for (SysUserRole userRole : userRoles){
            SysRole role = roleService.selectById(userRole.getRoleId());
            authorities.add(new SimpleGrantedAuthority(role.getName()));
        }
        //返回UserDeatils實現類
        return new User(user.getName(),user.getPassword(),authorities);
    }
}

6.2 WebSecurityConfig

該類是Spring Security的配置類,該類的三個註解分別是標識該類是配置類、開啟Security服務、開啟全域性Securtiy註解。

首先將我們自定義的userDetailsService注入進來,在configure()方法中使用auth.userDetailsService()方法替換預設的userDetailsService。

這裡我們還指定了密碼的加密方式(Spring Security 5.0強制要求設定),因為我們資料庫是明文儲存的,所以無需加密,如下所示:
 

package com.chwx.springbootspringsecurity.common;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
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.password.PasswordEncoder;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;

import javax.sql.DataSource;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private CustomUserDetailsService userDetailsService;


    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests()
                //如果有允許匿名訪問的url,填寫在下面
                //.antMatchers().permitAll()
        .anyRequest()
                .authenticated()
                //設定登入頁面
                .and().formLogin().loginPage("/login")
                //設定登陸成功頁面
        .defaultSuccessUrl("/").permitAll()
                // 自定義登陸使用者名稱和密碼引數,預設為username和password
//                .usernameParameter("username")
//                .passwordParameter("password")
        .and().logout().permitAll();
       
        // 關閉CSRF跨域
        http.csrf().disable();
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        // 設定攔截忽略資料夾,可以對靜態資源放行
        web.ignoring().antMatchers("/css/**","/js/**");
        super.configure(web);
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(new PasswordEncoder() {
            @Override
            public String encode(CharSequence charSequence) {
                
                return charSequence.toString();
                
            }

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

Step7 執行程式

注:如果你想要使用密碼加密功能的話,修改configure()方法如下:

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
     auth.userDetailsService(userDetailsService)
         .passwordEncoder(new PasswordEncoder() {
             @Override
             public String encode(CharSequence rawPassword) {
                 return new BCryptPasswordEncoder().encode(rawPassword);
             }

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