SpringSecurity-前後端分離教程

1、簡介

Spring Security 是 Spring 家族中的一個安全管理框架。相比與另外一個安全框架Shiro,它提供了更豐富的功能,社區資源也比Shiro豐富。

一般來說中大型的項目都是使用SpringSecurity 來做安全框架。小項目有Shiro的比較多,因爲相比與SpringSecurity,Shiro的上手更加的簡單。

一般Web應用的需要進行認證授權

  認證:驗證當前訪問系統的是不是本系統的用戶,並且要確認具體是哪個用戶

  授權:經過認證後判斷當前用戶是否有權限進行某個操作

而認證和授權也是SpringSecurity作爲安全框架的核心功能。

2、快速入門

1、準備工作

我們先要搭建一個簡單的SpringBoot工程

① 創建SpringBoot工程、添加依賴

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
</dependency>

② 創建Controller

@RestController
public class HelloController {

    @RequestMapping("/hello")
    public String hello(){
        return "hello";
    }
}

③ 啓動項目

引入依賴後我們在嘗試去訪問之前的接口就會自動跳轉到一個SpringSecurity的默認登陸頁面,默認用戶名是user,密碼會輸出在控制檯。必須登陸之後才能對接口進行訪問。

3、認證

1、登錄流程

 

2、認證原理

2.1、SpringSecurity完整流程

SpringSecurity的原理其實就是一個過濾器鏈,內部包含了提供各種功能的過濾器。這裏我們可以看看入門案例中的過濾器。

 

圖中只展示了核心過濾器,其它的非核心過濾器並沒有在圖中展示。

  UsernamePasswordAuthenticationFilter:負責處理我們在登陸頁面填寫了用戶名密碼後的登陸請求。入門案例的認證工作主要有它負責。

  ExceptionTranslationFilter:處理過濾器鏈中拋出的任何AccessDeniedException和AuthenticationException 。

  FilterSecurityInterceptor:負責權限校驗的過濾器。

我們可以通過Debug查看當前系統中SpringSecurity過濾器鏈中有哪些過濾器及它們的順序。

2.2、認證流程詳解

概念速查:

  Authentication接口: 它的實現類,表示當前訪問系統的用戶,封裝了用戶相關信息。

  AuthenticationManager接口:定義了認證Authentication的方法

  UserDetailsService接口:加載用戶特定數據的核心接口。裏面定義了一個根據用戶名查詢用戶信息的方法。

  UserDetails接口:提供核心用戶信息。通過UserDetailsService根據用戶名獲取處理的用戶信息要封裝成UserDetails對象返回。然後將這些信息封裝到Authentication對象中。

2.3、自定義實現認證流程分析

2.3.1、思路分析

登錄

  ①自定義登錄接口

    1、調用ProviderManager的方法進行認證 如果認證通過生成jwt

    2、把用戶信息存入redis中

  ②自定義UserDetailsService

    1、在這個實現類中去查詢數據庫

校驗:

  ①定義Jwt認證過濾器

    1、獲取token

    2、解析token獲取其中的userid

    3、從redis中獲取用戶信息

    4、存入SecurityContextHolder

2.3.2、準備工作

① 添加依賴

<!--redis依賴-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!--fastjson依賴-->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.33</version>
</dependency>
<!--jwt依賴-->
<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt</artifactId>
    <version>0.9.0</version>
</dependency>

② 添加Redis相關配置

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
import com.alibaba.fastjson.parser.ParserConfig;
import org.springframework.util.Assert;
import java.nio.charset.Charset;
/**
 * Redis使用FastJson序列化
 * 
 * @author sg
 */
public class FastJsonRedisSerializer<T> implements RedisSerializer<T>
{
    public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
    private Class<T> clazz;
    static {
        ParserConfig.getGlobalInstance().setAutoTypeSupport(true);
    }
    public FastJsonRedisSerializer(Class<T> clazz){
        super();
        this.clazz = clazz;
    }
    @Override
    public byte[] serialize(T t) throws SerializationException{
        if (t == null){
            return new byte[0];
        }
        return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(DEFAULT_CHARSET);
    }
    @Override
    public T deserialize(byte[] bytes) throws SerializationException{
        if (bytes == null || bytes.length <= 0){
            return null;
        }
        String str = new String(bytes, DEFAULT_CHARSET);
        return JSON.parseObject(str, clazz);
    }
    protected JavaType getJavaType(Class<?> clazz){
        return TypeFactory.defaultInstance().constructType(clazz);
    }
}
@Configuration
public class RedisConfig {
    @Bean
    @SuppressWarnings(value = { "unchecked", "rawtypes" })
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory){
        RedisTemplate<Object, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory);
        FastJsonRedisSerializer serializer = new FastJsonRedisSerializer(Object.class);
        // 使用StringRedisSerializer來序列化和反序列化redis的key值
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(serializer);
        // Hash的key也採用StringRedisSerializer的序列化方式
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(serializer);
        template.afterPropertiesSet();
        return template;
    }
}

③ 響應類

@JsonInclude(JsonInclude.Include.NON_NULL)
public class ResponseResult<T> {
    /**
     * 狀態碼
     */
    private Integer code;
    /**
     * 提示信息,如果有錯誤時,前端可以獲取該字段進行提示
     */
    private String msg;
    /**
     * 查詢到的結果數據,
     */
    private T data;

    public ResponseResult(Integer code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    public ResponseResult(Integer code, T data) {
        this.code = code;
        this.data = data;
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    public ResponseResult(Integer code, String msg, T data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }
}
View Code

④ Jwt工具類

/**
 * JWT工具類
 */
public class JwtUtil {
    //有效期爲
    public static final long JWT_TTL = 60 * 60 *1000L;
    // 60 * 60 *1000  一個小時
    //設置祕鑰明文
    public static final String JWT_KEY = "sun_key";
    public static String getUUID(){
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        return token;
    }
    /**
     * 生成jtw
     * @param subject token中要存放的數據(json格式)
     * @return
     */
    public static String createJWT(String subject) {
        JwtBuilder builder = getJwtBuilder(subject, null, getUUID());
        // 設置過期時間
        return builder.compact();
    }
    /**
     * 生成jtw
     * @param subject token中要存放的數據(json格式)
     * @param ttlMillis token超時時間
     * @return
     */
    public static String createJWT(String subject, long ttlMillis) {
        JwtBuilder builder = getJwtBuilder(subject, ttlMillis, getUUID());
        // 設置過期時間
        return builder.compact();
    }

    private static JwtBuilder getJwtBuilder(String subject, long ttlMillis, String uuid) {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        SecretKey secretKey = generalKey();
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        if(ttlMillis==null){
            ttlMillis=JwtUtil.JWT_TTL;
        }
        long expMillis = nowMillis + ttlMillis;
        Date expDate = new Date(expMillis);
        return Jwts.builder()
                    .setId(uuid)              //唯一的ID
                    .setSubject(subject)   // 主題  可以是JSON數據
                    .setIssuer("sun")     // 簽發者
                    .setIssuedAt(now)      // 簽發時間
                    .signWith(signatureAlgorithm, secretKey) //使用HS256對稱加密算法簽名, 第二個參數爲祕鑰
                    .setExpiration(expDate);
    }
    /**
     * 創建token
     * @param id
     * @param subject
     * @param ttlMillis
     * @return
     */
    public static String createJWT(String id, String subject, long ttlMillis) {
        JwtBuilder builder = getJwtBuilder(subject, ttlMillis, id);
        // 設置過期時間
        return builder.compact();
    }

    public static void main(String[] args) throws Exception {
        String token = "eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiJjYWM2ZDVhZi1mNjVlLTQ0MDAtYjcxMi0zYWEwOGIyOTIwYjQiLCJzdWIiOiJzZyIsImlzcyI6InNnIiwiaWF0IjoxNjM4MTA2NzEyLCJleHAiOjE2MzgxMTAzMTJ9.JVsSbkP94wuczb4QryQbAke3ysBDIL5ou8fWsbt_ebg";
        Claims claims = parseJWT(token);
        System.out.println(claims);
    }
    /**
     * 生成加密後的祕鑰 secretKey
     * @return
     */
    public static SecretKey generalKey() {
        byte[] encodedKey = Base64.getDecoder().decode(JwtUtil.JWT_KEY);
        SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
        return key;
    }
    /**
     * 解析
     *
     * @param jwt
     * @return
     * @throws Exception
     */
    public static Claims parseJWT(String jwt) throws Exception {
        SecretKey secretKey = generalKey();
        return Jwts.parser()
                        .setSigningKey(secretKey)
                        .parseClaimsJws(jwt)
                        .getBody();
    }
}
View Code

⑤ Redis工具類

@SuppressWarnings(value = { "unchecked", "rawtypes" })
@Component
public class RedisCache
{
    @Autowired
    public RedisTemplate redisTemplate;

    /**
     * 緩存基本的對象,Integer、String、實體類等
     *
     * @param key 緩存的鍵值
     * @param value 緩存的值
     */
    public <T> void setCacheObject(final String key, final T value)
    {
        redisTemplate.opsForValue().set(key, value);
    }

    /**
     * 緩存基本的對象,Integer、String、實體類等
     *
     * @param key 緩存的鍵值
     * @param value 緩存的值
     * @param timeout 時間
     * @param timeUnit 時間顆粒度
     */
    public <T> void setCacheObject(final String key, final T value, final Integer timeout, final TimeUnit timeUnit)
    {
        redisTemplate.opsForValue().set(key, value, timeout, timeUnit);
    }

    /**
     * 設置有效時間
     *
     * @param key Redis鍵
     * @param timeout 超時時間
     * @return true=設置成功;false=設置失敗
     */
    public boolean expire(final String key, final long timeout)
    {
        return expire(key, timeout, TimeUnit.SECONDS);
    }

    /**
     * 設置有效時間
     *
     * @param key Redis鍵
     * @param timeout 超時時間
     * @param unit 時間單位
     * @return true=設置成功;false=設置失敗
     */
    public boolean expire(final String key, final long timeout, final TimeUnit unit)
    {
        return redisTemplate.expire(key, timeout, unit);
    }

    /**
     * 獲得緩存的基本對象。
     *
     * @param key 緩存鍵值
     * @return 緩存鍵值對應的數據
     */
    public <T> T getCacheObject(final String key)
    {
        ValueOperations<String, T> operation = redisTemplate.opsForValue();
        return operation.get(key);
    }

    /**
     * 刪除單個對象
     *
     * @param key
     */
    public boolean deleteObject(final String key)
    {
        return redisTemplate.delete(key);
    }

    /**
     * 刪除集合對象
     *
     * @param collection 多個對象
     * @return
     */
    public long deleteObject(final Collection collection)
    {
        return redisTemplate.delete(collection);
    }

    /**
     * 緩存List數據
     *
     * @param key 緩存的鍵值
     * @param dataList 待緩存的List數據
     * @return 緩存的對象
     */
    public <T> long setCacheList(final String key, final List<T> dataList)
    {
        Long count = redisTemplate.opsForList().rightPushAll(key, dataList);
        return count == null ? 0 : count;
    }

    /**
     * 獲得緩存的list對象
     *
     * @param key 緩存的鍵值
     * @return 緩存鍵值對應的數據
     */
    public <T> List<T> getCacheList(final String key)
    {
        return redisTemplate.opsForList().range(key, 0, -1);
    }

    /**
     * 緩存Set
     *
     * @param key 緩存鍵值
     * @param dataSet 緩存的數據
     * @return 緩存數據的對象
     */
    public <T> BoundSetOperations<String, T> setCacheSet(final String key, final Set<T> dataSet)
    {
        BoundSetOperations<String, T> setOperation = redisTemplate.boundSetOps(key);
        Iterator<T> it = dataSet.iterator();
        while (it.hasNext())
        {
            setOperation.add(it.next());
        }
        return setOperation;
    }

    /**
     * 獲得緩存的set
     *
     * @param key
     * @return
     */
    public <T> Set<T> getCacheSet(final String key)
    {
        return redisTemplate.opsForSet().members(key);
    }

    /**
     * 緩存Map
     *
     * @param key
     * @param dataMap
     */
    public <T> void setCacheMap(final String key, final Map<String, T> dataMap)
    {
        if (dataMap != null) {
            redisTemplate.opsForHash().putAll(key, dataMap);
        }
    }

    /**
     * 獲得緩存的Map
     *
     * @param key
     * @return
     */
    public <T> Map<String, T> getCacheMap(final String key)
    {
        return redisTemplate.opsForHash().entries(key);
    }

    /**
     * 往Hash中存入數據
     *
     * @param key Redis鍵
     * @param hKey Hash鍵
     * @param value 值
     */
    public <T> void setCacheMapValue(final String key, final String hKey, final T value)
    {
        redisTemplate.opsForHash().put(key, hKey, value);
    }

    /**
     * 獲取Hash中的數據
     *
     * @param key Redis鍵
     * @param hKey Hash鍵
     * @return Hash中的對象
     */
    public <T> T getCacheMapValue(final String key, final String hKey)
    {
        HashOperations<String, String, T> opsForHash = redisTemplate.opsForHash();
        return opsForHash.get(key, hKey);
    }

    /**
     * 刪除Hash中的數據
     * 
     * @param key
     * @param hkey
     */
    public void delCacheMapValue(final String key, final String hkey)
    {
        HashOperations hashOperations = redisTemplate.opsForHash();
        hashOperations.delete(key, hkey);
    }

    /**
     * 獲取多個Hash中的數據
     *
     * @param key Redis鍵
     * @param hKeys Hash鍵集合
     * @return Hash對象集合
     */
    public <T> List<T> getMultiCacheMapValue(final String key, final Collection<Object> hKeys)
    {
        return redisTemplate.opsForHash().multiGet(key, hKeys);
    }

    /**
     * 獲得緩存的基本對象列表
     *
     * @param pattern 字符串前綴
     * @return 對象列表
     */
    public Collection<String> keys(final String pattern)
    {
        return redisTemplate.keys(pattern);
    }
}
View Code

⑥ 將字符串響應到客戶端工具類

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

public class WebUtils
{
    /**
     * 將字符串渲染到客戶端
     * 
     * @param response 渲染對象
     * @param string 待渲染的字符串
     * @return null
     */
    public static String renderString(HttpServletResponse response, String string) {
        try
        {
            response.setStatus(200);
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            response.getWriter().print(string);
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return null;
    }
}

⑦ 實體類(對應數據庫中的用戶表)

import java.io.Serializable;
import java.util.Date;


/**
 * 用戶表(User)實體類
 *
 * @author 三更
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User implements Serializable {
    private static final long serialVersionUID = -40356785423868312L;
    
    /**
    * 主鍵
    */
    private Long id;
    /**
    * 用戶名
    */
    private String userName;
    /**
    * 暱稱
    */
    private String nickName;
    /**
    * 密碼
    */
    private String password;
    /**
    * 賬號狀態(0正常 1停用)
    */
    private String status;
    /**
    * 郵箱
    */
    private String email;
    /**
    * 手機號
    */
    private String phonenumber;
    /**
    * 用戶性別(0男,1女,2未知)
    */
    private String sex;
    /**
    * 頭像
    */
    private String avatar;
    /**
    * 用戶類型(0管理員,1普通用戶)
    */
    private String userType;
    /**
    * 創建人的用戶id
    */
    private Long createBy;
    /**
    * 創建時間
    */
    private Date createTime;
    /**
    * 更新人
    */
    private Long updateBy;
    /**
    * 更新時間
    */
    private Date updateTime;
    /**
    * 刪除標誌(0代表未刪除,1代表已刪除)
    */
    private Integer delFlag;
}
View Code

2.3.3、具體實現

1、數據庫校驗用戶

從之前的分析我們可以知道,我們可以自定義一個UserDetailsService,讓SpringSecurity使用我們的UserDetailsService。我們自己的UserDetailsService可以從數據庫中查詢用戶名和密碼。

 

準備工作

1、創建用戶表:

CREATE TABLE `sys_user` (
  `id` BIGINT(20) NOT NULL AUTO_INCREMENT COMMENT '主鍵',
  `user_name` VARCHAR(64) NOT NULL DEFAULT 'NULL' COMMENT '用戶名',
  `nick_name` VARCHAR(64) NOT NULL DEFAULT 'NULL' COMMENT '暱稱',
  `password` VARCHAR(64) NOT NULL DEFAULT 'NULL' COMMENT '密碼',
  `status` CHAR(1) DEFAULT '0' COMMENT '賬號狀態(0正常 1停用)',
  `email` VARCHAR(64) DEFAULT NULL COMMENT '郵箱',
  `phonenumber` VARCHAR(32) DEFAULT NULL COMMENT '手機號',
  `sex` CHAR(1) DEFAULT NULL COMMENT '用戶性別(0男,1女,2未知)',
  `avatar` VARCHAR(128) DEFAULT NULL COMMENT '頭像',
  `user_type` CHAR(1) NOT NULL DEFAULT '1' COMMENT '用戶類型(0管理員,1普通用戶)',
  `create_by` BIGINT(20) DEFAULT NULL COMMENT '創建人的用戶id',
  `create_time` DATETIME DEFAULT NULL COMMENT '創建時間',
  `update_by` BIGINT(20) DEFAULT NULL COMMENT '更新人',
  `update_time` DATETIME DEFAULT NULL COMMENT '更新時間',
  `del_flag` INT(11) DEFAULT '0' COMMENT '刪除標誌(0代表未刪除,1代表已刪除)',
  PRIMARY KEY (`id`)
) ENGINE=INNODB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COMMENT='用戶表'

2、引入MybatisPlus和mysql驅動的依賴:

 <dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.4.3</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>

3、配置數據庫信息:

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/sg_security?characterEncoding=utf-8&serverTimezone=UTC
    username: root
    password: root
    driver-class-name: com.mysql.cj.jdbc.Driver

4、定義Mapper接口:

public interface UserMapper extends BaseMapper<User> {
}

5、修改User實體類:

類名上加@TableName(value = "sys_user") ,id字段上加 @TableId

6、配置Mapper掃描:

@SpringBootApplication
@MapperScan("com.sangeng.mapper")
public class SimpleSecurityApplication {
    public static void main(String[] args) {
        ConfigurableApplicationContext run = SpringApplication.run(SimpleSecurityApplication.class);
        System.out.println(run);
    }
}

核心代碼實現

1、創建一個類實現UserDetailsService接口,重寫其中的方法。更加用戶名從數據庫中查詢用戶信息

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根據用戶名查詢用戶信息
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUserName,username);
        User user = userMapper.selectOne(wrapper);
        //如果查詢不到數據就通過拋出異常來給出提示
        if(Objects.isNull(user)){
            throw new RuntimeException("用戶名或密碼錯誤");
        }
        //TODO 根據用戶查詢權限信息 添加到LoginUser中
        
        //封裝成UserDetails對象返回 
        return new LoginUser(user);
    }
}

2、因爲UserDetailsService方法的返回值是UserDetails類型,所以需要定義一個類,實現該接口,把用戶信息封裝在其中。

@Data
@NoArgsConstructor
@AllArgsConstructor
public class LoginUser implements UserDetails {

    private User user;


    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return null;
    }

    @Override
    public String getPassword() {
        return user.getPassword();
    }

    @Override
    public String getUsername() {
        return user.getUserName();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}
View Code

注意:如果要測試,需要往用戶表中寫入用戶數據,並且如果你想讓用戶的密碼是明文存儲,需要在密碼前加{noop}。例如

這樣登陸的時候就可以用sg作爲用戶名,1234作爲密碼來登陸了。

2、密碼加密存儲

實際項目中我們不會把密碼明文存儲在數據庫中。

默認使用的PasswordEncoder要求數據庫中的密碼格式爲:{id}password 。它會根據id去判斷密碼的加密方式。但是我們一般不會採用這種方式。所以就需要替換PasswordEncoder。

我們一般使用SpringSecurity爲我們提供的BCryptPasswordEncoder。

我們只需要使用把BCryptPasswordEncoder對象注入Spring容器中,SpringSecurity就會使用該PasswordEncoder來進行密碼校驗。

我們可以定義一個SpringSecurity的配置類,SpringSecurity要求這個配置類要繼承WebSecurityConfigurerAdapter。

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

}
3、登錄接口

接下我們需要自定義登陸接口,然後讓SpringSecurity對這個接口放行,讓用戶訪問這個接口的時候不用登錄也能訪問。

​ 在接口中我們通過AuthenticationManager的authenticate方法來進行用戶認證,所以需要在SecurityConfig中配置把AuthenticationManager注入容器。

​ 認證成功的話要生成一個jwt,放入響應中返回。並且爲了讓用戶下回請求時能通過jwt識別出具體的是哪個用戶,我們需要把用戶信息存入redis,可以把用戶id作爲key。

@RestController
public class LoginController {

    @Autowired
    private LoginServcie loginServcie;

    @PostMapping("/user/login")
    public ResponseResult login(@RequestBody User user){
        return loginServcie.login(user);
    }
}
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                //關閉csrf
                .csrf().disable()
                //不通過Session獲取SecurityContext
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                // 對於登錄接口 允許匿名訪問
                .antMatchers("/user/login").anonymous()
                // 除上面外的所有請求全部需要鑑權認證
                .anyRequest().authenticated();
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
}
@Service
public class LoginServiceImpl implements LoginServcie {

    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private RedisCache redisCache;

    @Override
    public ResponseResult login(User user) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(),user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        if(Objects.isNull(authenticate)){
            throw new RuntimeException("用戶名或密碼錯誤");
        }
        //使用userid生成token
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userId = loginUser.getUser().getId().toString();
        String jwt = JwtUtil.createJWT(userId);
        //authenticate存入redis
        redisCache.setCacheObject("login:"+userId,loginUser);
        //把token響應給前端
        HashMap<String,String> map = new HashMap<>();
        map.put("token",jwt);
        return new ResponseResult(200,"登陸成功",map);
    }
}
4、認證過濾器

我們需要自定義一個過濾器,這個過濾器會去獲取請求頭中的token,對token進行解析取出其中的userid。

使用userid去redis中獲取對應的LoginUser對象。

然後封裝Authentication對象存入SecurityContextHolder

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //獲取token
        String token = request.getHeader("token");
        if (!StringUtils.hasText(token)) {
            //放行
            filterChain.doFilter(request, response);
            return;
        }
        //解析token
        String userid;
        try {
            Claims claims = JwtUtil.parseJWT(token);
            userid = claims.getSubject();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("token非法");
        }
        //從redis中獲取用戶信息
        String redisKey = "login:" + userid;
        LoginUser loginUser = redisCache.getCacheObject(redisKey);
        if(Objects.isNull(loginUser)){
            throw new RuntimeException("用戶未登錄");
        }
        //存入SecurityContextHolder
        //TODO 獲取權限信息封裝到Authentication中
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(loginUser,null,null);
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        //放行
        filterChain.doFilter(request, response);
    }
}
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {


    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }


    @Autowired
    JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                //關閉csrf
                .csrf().disable()
                //不通過Session獲取SecurityContext
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                // 對於登錄接口 允許匿名訪問
                .antMatchers("/user/login").anonymous()
                // 除上面外的所有請求全部需要鑑權認證
                .anyRequest().authenticated();

        //把token校驗過濾器添加到過濾器鏈中
        http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
}
5、退出登陸

我們只需要定義一個登陸接口,然後獲取SecurityContextHolder中的認證信息,刪除redis中對應的數據即可。

@Service
public class LoginServiceImpl implements LoginServcie {

    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private RedisCache redisCache;

    @Override
    public ResponseResult login(User user) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(),user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        if(Objects.isNull(authenticate)){
            throw new RuntimeException("用戶名或密碼錯誤");
        }
        //使用userid生成token
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userId = loginUser.getUser().getId().toString();
        String jwt = JwtUtil.createJWT(userId);
        //authenticate存入redis
        redisCache.setCacheObject("login:"+userId,loginUser);
        //把token響應給前端
        HashMap<String,String> map = new HashMap<>();
        map.put("token",jwt);
        return new ResponseResult(200,"登陸成功",map);
    }

    @Override
    public ResponseResult logout() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Long userid = loginUser.getUser().getId();
        redisCache.deleteObject("login:"+userid);
        return new ResponseResult(200,"退出成功");
    }
}

三、授權

1、權限系統的作用

  例如一個學校圖書館的管理系統,如果是普通學生登錄就能看到借書還書相關的功能,不可能讓他看到並且去使用添加書籍信息,刪除書籍信息等功能。但是如果是一個圖書館管理員的賬號登錄了,應該就能看到並使用添加書籍信息,刪除書籍信息等功能。

總結起來就是不同的用戶可以使用不同的功能。這就是權限系統要去實現的效果。

我們不能只依賴前端去判斷用戶的權限來選擇顯示哪些菜單哪些按鈕。因爲如果只是這樣,如果有人知道了對應功能的接口地址就可以不通過前端,直接去發送請求來實現相關功能操作。

所以我們還需要在後臺進行用戶權限的判斷,判斷當前用戶是否有相應的權限,必須具有所需權限才能進行相應的操作。

2、授權基本流程

在SpringSecurity中,會使用默認的FilterSecurityInterceptor來進行權限校驗。在FilterSecurityInterceptor中會從SecurityContextHolder獲取其中的Authentication,然後獲取其中的權限信息。當前用戶是否擁有訪問當前資源所需的權限。

所以我們在項目中只需要把當前登錄用戶的權限信息也存入Authentication。

然後設置我們的資源所需要的權限即可。

3、授權實現

3.1、限制訪問資源所需權限

SpringSecurity爲我們提供了基於註解的權限控制方案,這也是我們項目中主要採用的方式。我們可以使用註解去指定訪問對應的資源所需的權限。但是要使用它我們需要先開啓相關配置。

@EnableGlobalMethodSecurity(prePostEnabled = true)

然後就可以使用對應的註解。@PreAuthorize

@RestController
public class HelloController {

    @RequestMapping("/hello")
    @PreAuthorize("hasAuthority('test')")
    public String hello(){
        return "hello";
    }
}

3.2、封裝權限信息

我們前面在寫UserDetailsServiceImpl的時候說過,在查詢出用戶後還要獲取對應的權限信息,封裝到UserDetails中返回。

我們先直接把權限信息寫死封裝到UserDetails中進行測試。

我們之前定義了UserDetails的實現類LoginUser,想要讓其能封裝權限信息就要對其進行修改。

import com.alibaba.fastjson.annotation.JSONField;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author 三更  B站: https://space.bilibili.com/663528522
 */
@Data
@NoArgsConstructor
public class LoginUser implements UserDetails {

    private User user;
        
    //存儲權限信息
    private List<String> permissions;
    
    
    public LoginUser(User user,List<String> permissions) {
        this.user = user;
        this.permissions = permissions;
    }


    //存儲SpringSecurity所需要的權限信息的集合
    @JSONField(serialize = false)
    private List<GrantedAuthority> authorities;

    @Override
    public  Collection<? extends GrantedAuthority> getAuthorities() {
        if(authorities!=null){
            return authorities;
        }
        //把permissions中字符串類型的權限信息轉換成GrantedAuthority對象存入authorities中
        authorities = permissions.stream().
                map(SimpleGrantedAuthority::new)
                .collect(Collectors.toList());
        return authorities;
    }

    @Override
    public String getPassword() {
        return user.getPassword();
    }

    @Override
    public String getUsername() {
        return user.getUserName();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}
View Code

LoginUser修改完後我們就可以在UserDetailsServiceImpl中去把權限信息封裝到LoginUser中了。我們寫死權限進行測試,後面我們再從數據庫中查詢權限信息。

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUserName,username);
        User user = userMapper.selectOne(wrapper);
        if(Objects.isNull(user)){
            throw new RuntimeException("用戶名或密碼錯誤");
        }
        //TODO 根據用戶查詢權限信息 添加到LoginUser中
        List<String> list = new ArrayList<>(Arrays.asList("test"));
        return new LoginUser(user,list);
    }
}

3.3、從數據庫查詢權限信息

1、RBAC權限模型

RBAC權限模型(Role-Based Access Control)即:基於角色的權限控制。這是目前最常被開發者使用也是相對易用、通用權限模型。

2、準備工作

rbac需要創建表sql:

CREATE DATABASE /*!32312 IF NOT EXISTS*/`sg_security` /*!40100 DEFAULT CHARACTER SET utf8mb4 */;

USE `sg_security`;

/*Table structure for table `sys_menu` */

DROP TABLE IF EXISTS `sys_menu`;

CREATE TABLE `sys_menu` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `menu_name` varchar(64) NOT NULL DEFAULT 'NULL' COMMENT '菜單名',
  `path` varchar(200) DEFAULT NULL COMMENT '路由地址',
  `component` varchar(255) DEFAULT NULL COMMENT '組件路徑',
  `visible` char(1) DEFAULT '0' COMMENT '菜單狀態(0顯示 1隱藏)',
  `status` char(1) DEFAULT '0' COMMENT '菜單狀態(0正常 1停用)',
  `perms` varchar(100) DEFAULT NULL COMMENT '權限標識',
  `icon` varchar(100) DEFAULT '#' COMMENT '菜單圖標',
  `create_by` bigint(20) DEFAULT NULL,
  `create_time` datetime DEFAULT NULL,
  `update_by` bigint(20) DEFAULT NULL,
  `update_time` datetime DEFAULT NULL,
  `del_flag` int(11) DEFAULT '0' COMMENT '是否刪除(0未刪除 1已刪除)',
  `remark` varchar(500) DEFAULT NULL COMMENT '備註',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COMMENT='菜單表';

/*Table structure for table `sys_role` */

DROP TABLE IF EXISTS `sys_role`;

CREATE TABLE `sys_role` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `name` varchar(128) DEFAULT NULL,
  `role_key` varchar(100) DEFAULT NULL COMMENT '角色權限字符串',
  `status` char(1) DEFAULT '0' COMMENT '角色狀態(0正常 1停用)',
  `del_flag` int(1) DEFAULT '0' COMMENT 'del_flag',
  `create_by` bigint(200) DEFAULT NULL,
  `create_time` datetime DEFAULT NULL,
  `update_by` bigint(200) DEFAULT NULL,
  `update_time` datetime DEFAULT NULL,
  `remark` varchar(500) DEFAULT NULL COMMENT '備註',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COMMENT='角色表';

/*Table structure for table `sys_role_menu` */

DROP TABLE IF EXISTS `sys_role_menu`;

CREATE TABLE `sys_role_menu` (
  `role_id` bigint(200) NOT NULL AUTO_INCREMENT COMMENT '角色ID',
  `menu_id` bigint(200) NOT NULL DEFAULT '0' COMMENT '菜單id',
  PRIMARY KEY (`role_id`,`menu_id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4;

/*Table structure for table `sys_user` */

DROP TABLE IF EXISTS `sys_user`;

CREATE TABLE `sys_user` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主鍵',
  `user_name` varchar(64) NOT NULL DEFAULT 'NULL' COMMENT '用戶名',
  `nick_name` varchar(64) NOT NULL DEFAULT 'NULL' COMMENT '暱稱',
  `password` varchar(64) NOT NULL DEFAULT 'NULL' COMMENT '密碼',
  `status` char(1) DEFAULT '0' COMMENT '賬號狀態(0正常 1停用)',
  `email` varchar(64) DEFAULT NULL COMMENT '郵箱',
  `phonenumber` varchar(32) DEFAULT NULL COMMENT '手機號',
  `sex` char(1) DEFAULT NULL COMMENT '用戶性別(0男,1女,2未知)',
  `avatar` varchar(128) DEFAULT NULL COMMENT '頭像',
  `user_type` char(1) NOT NULL DEFAULT '1' COMMENT '用戶類型(0管理員,1普通用戶)',
  `create_by` bigint(20) DEFAULT NULL COMMENT '創建人的用戶id',
  `create_time` datetime DEFAULT NULL COMMENT '創建時間',
  `update_by` bigint(20) DEFAULT NULL COMMENT '更新人',
  `update_time` datetime DEFAULT NULL COMMENT '更新時間',
  `del_flag` int(11) DEFAULT '0' COMMENT '刪除標誌(0代表未刪除,1代表已刪除)',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COMMENT='用戶表';

/*Table structure for table `sys_user_role` */

DROP TABLE IF EXISTS `sys_user_role`;

CREATE TABLE `sys_user_role` (
  `user_id` bigint(200) NOT NULL AUTO_INCREMENT COMMENT '用戶id',
  `role_id` bigint(200) NOT NULL DEFAULT '0' COMMENT '角色id',
  PRIMARY KEY (`user_id`,`role_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
View Code

menu實體類創建:

/**
 * 菜單表(Menu)實體類
 *
 * @author makejava
 * @since 2021-11-24 15:30:08
 */
@TableName(value="sys_menu")
@Data
@AllArgsConstructor
@NoArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Menu implements Serializable {
    private static final long serialVersionUID = -54979041104113736L;
    
        @TableId
    private Long id;
    /**
    * 菜單名
    */
    private String menuName;
    /**
    * 路由地址
    */
    private String path;
    /**
    * 組件路徑
    */
    private String component;
    /**
    * 菜單狀態(0顯示 1隱藏)
    */
    private String visible;
    /**
    * 菜單狀態(0正常 1停用)
    */
    private String status;
    /**
    * 權限標識
    */
    private String perms;
    /**
    * 菜單圖標
    */
    private String icon;
    
    private Long createBy;
    
    private Date createTime;
    
    private Long updateBy;
    
    private Date updateTime;
    /**
    * 是否刪除(0未刪除 1已刪除)
    */
    private Integer delFlag;
    /**
    * 備註
    */
    private String remark;
}
View Code

3、代碼實現

我們只需要根據用戶id去查詢到其所對應的權限信息即可。所以我們可以先定義個mapper,其中提供一個方法可以根據userid查詢權限信息。

public interface MenuMapper extends BaseMapper<Menu> {
    List<String> selectPermsByUserId(Long id);
}

尤其是自定義方法,所以需要創建對應的mapper文件,定義對應的sql語句

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.sangeng.mapper.MenuMapper">


    <select id="selectPermsByUserId" resultType="java.lang.String">
        SELECT
            DISTINCT m.`perms`
        FROM
            sys_user_role ur
            LEFT JOIN `sys_role` r ON ur.`role_id` = r.`id`
            LEFT JOIN `sys_role_menu` rm ON ur.`role_id` = rm.`role_id`
            LEFT JOIN `sys_menu` m ON m.`id` = rm.`menu_id`
        WHERE
            user_id = #{userid}
            AND r.`status` = 0
            AND m.`status` = 0
    </select>
</mapper>

在application.yml中配置mapperXML文件的位置

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/sg_security?characterEncoding=utf-8&serverTimezone=UTC
    username: root
    password: root
    driver-class-name: com.mysql.cj.jdbc.Driver
  redis:
    host: localhost
    port: 6379
mybatis-plus:
  mapper-locations: classpath*:/mapper/**/*.xml 

然後我們可以在UserDetailsServiceImpl中去調用該mapper的方法查詢權限信息封裝到LoginUser對象中即可。

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private MenuMapper menuMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUserName,username);
        User user = userMapper.selectOne(wrapper);
        if(Objects.isNull(user)){
            throw new RuntimeException("用戶名或密碼錯誤");
        }
        List<String> permissionKeyList =  menuMapper.selectPermsByUserId(user.getId());
//        //測試寫法
//        List<String> list = new ArrayList<>(Arrays.asList("test"));
        return new LoginUser(user,permissionKeyList);
    }
}

四、自定義失敗處理

我們還希望在認證失敗或者是授權失敗的情況下也能和我們的接口一樣返回相同結構的json,這樣可以讓前端能對響應進行統一的處理。要實現這個功能我們需要知道SpringSecurity的異常處理機制。

在SpringSecurity中,如果我們在認證或者授權的過程中出現了異常會被ExceptionTranslationFilter捕獲到。在ExceptionTranslationFilter中會去判斷是認證失敗還是授權失敗出現的異常。

如果是認證過程中出現的異常會被封裝成AuthenticationException然後調用AuthenticationEntryPoint對象的方法去進行異常處理。

如果是授權過程中出現的異常會被封裝成AccessDeniedException然後調用AccessDeniedHandler對象的方法去進行異常處理。

所以如果我們需要自定義異常處理,我們只需要自定義AuthenticationEntryPoint和AccessDeniedHandler然後配置給SpringSecurity即可。

① 自定義實現類

授權失敗:

@Component
public class AccessDeniedHandlerImpl implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        ResponseResult result = new ResponseResult(HttpStatus.FORBIDDEN.value(), "權限不足");
        String json = JSON.toJSONString(result);
        WebUtils.renderString(response,json);
    }
}

認證失敗:

@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        ResponseResult result = new ResponseResult(HttpStatus.UNAUTHORIZED.value(), "認證失敗請重新登錄");
        String json = JSON.toJSONString(result);
        WebUtils.renderString(response,json);
    }
}

② 配置給SpringSecurity

先注入對應的處理器:

@Autowired
private AuthenticationEntryPoint authenticationEntryPoint;

@Autowired
private AccessDeniedHandler accessDeniedHandler;

然後我們可以使用HttpSecurity對象的方法去配置。

http.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint).accessDeniedHandler(accessDeniedHandler);

五、跨域

瀏覽器出於安全的考慮,使用 XMLHttpRequest對象發起 HTTP請求時必須遵守同源策略,否則就是跨域的HTTP請求,默認情況下是被禁止的。 同源策略要求源相同才能正常進行通信,即協議、域名、端口號都完全一致。

前後端分離項目,前端項目和後端項目一般都不是同源的,所以肯定會存在跨域請求的問題。

所以我們就要處理一下,讓前端能進行跨域請求。

① 先對SpringBoot配置,運行跨域請求

@Configuration
public class CorsConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
      // 設置允許跨域的路徑
        registry.addMapping("/**")
                // 設置允許跨域請求的域名
                .allowedOriginPatterns("*")
                // 是否允許cookie
                .allowCredentials(true)
                // 設置允許的請求方式
                .allowedMethods("GET", "POST", "DELETE", "PUT")
                // 設置允許的header屬性
                .allowedHeaders("*")
                // 跨域允許時間
                .maxAge(3600);
    }
}

② 開啓SpringSecurity的跨域訪問

由於我們的資源都會收到SpringSecurity的保護,所以想要跨域訪問還要讓SpringSecurity運行跨域訪問。

 @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                //關閉csrf
                .csrf().disable()
                //不通過Session獲取SecurityContext
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                // 對於登錄接口 允許匿名訪問
                .antMatchers("/user/login").anonymous()
                // 除上面外的所有請求全部需要鑑權認證
                .anyRequest().authenticated();

        //添加過濾器
        http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);

        //配置異常處理器
        http.exceptionHandling()
                //配置認證失敗處理器
                .authenticationEntryPoint(authenticationEntryPoint)
                .accessDeniedHandler(accessDeniedHandler);

        //允許跨域
        http.cors();
    }

六、遺留小問題

1、其它權限校驗方法

我們前面都是使用@PreAuthorize註解,然後在在其中使用的是hasAuthority方法進行校驗。SpringSecurity還爲我們提供了其它方法例如:hasAnyAuthority,hasRole,hasAnyRole等。

這裏我們先不急着去介紹這些方法,我們先去理解hasAuthority的原理,然後再去學習其他方法你就更容易理解,而不是死記硬背區別。並且我們也可以選擇定義校驗方法,實現我們自己的校驗邏輯。

hasAuthority方法實際是執行到了SecurityExpressionRoot的hasAuthority,大家只要斷點調試既可知道它內部的校驗原理。

它內部其實是調用authentication的getAuthorities方法獲取用戶的權限列表。然後判斷我們存入的方法參數數據在權限列表中。

hasAnyAuthority方法可以傳入多個權限,只有用戶有其中任意一個權限都可以訪問對應資源。

@PreAuthorize("hasAnyAuthority('admin','test','system:dept:list')")
public String hello(){
     return "hello";
}

hasRole要求有對應的角色纔可以訪問,但是它內部會把我們傳入的參數拼接上 ROLE_ 後再去比較。所以這種情況下要用用戶對應的權限也要有 ROLE_ 這個前綴纔可以。

@PreAuthorize("hasRole('system:dept:list')")
public String hello(){
    return "hello";
}

hasAnyRole 有任意的角色就可以訪問。它內部也會把我們傳入的參數拼接上 ROLE_ 後再去比較。所以這種情況下要用用戶對應的權限也要有 ROLE_ 這個前綴纔可以。

@PreAuthorize("hasAnyRole('admin','system:dept:list')")
public String hello(){
   return "hello";
}

2、自定義權限校驗方法

也可以定義自己的權限校驗方法,在@PreAuthorize註解中使用我們的方法。

@Component("ex")
public class SGExpressionRoot {
    public boolean hasAuthority(String authority){
        //獲取當前用戶的權限
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        List<String> permissions = loginUser.getPermissions();
        //判斷用戶權限集合中是否存在authority
        return permissions.contains(authority);
    }
}

在SPEL表達式中使用 @ex相當於獲取容器中bean的名字未ex的對象。然後再調用這個對象的hasAuthority方法

@RequestMapping("/hello")
@PreAuthorize("@ex.hasAuthority('system:dept:list')")
public String hello(){
    return "hello";
}

3、基於配置的權限控制

我們也可以在配置類中使用使用配置的方式對資源進行權限控制。

@Override
protected void configure(HttpSecurity http) throws Exception {
        http
                //關閉csrf
                .csrf().disable()
                //不通過Session獲取SecurityContext
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                // 對於登錄接口 允許匿名訪問
                .antMatchers("/user/login").anonymous()
                .antMatchers("/testCors").hasAuthority("system:dept:list222")
                // 除上面外的所有請求全部需要鑑權認證
                .anyRequest().authenticated();

        //添加過濾器
        http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);

        //配置異常處理器
        http.exceptionHandling()
                //配置認證失敗處理器
                .authenticationEntryPoint(authenticationEntryPoint)
                .accessDeniedHandler(accessDeniedHandler);

        //允許跨域
        http.cors();
    }

4、CSRF

CSRF是指跨站請求僞造(Cross-site request forgery),是web常見的攻擊之一。

https://blog.csdn.net/freeking101/article/details/86537087

SpringSecurity去防止CSRF攻擊的方式就是通過csrf_token。後端會生成一個csrf_token,前端發起請求的時候需要攜帶這個csrf_token,後端會有過濾器進行校驗,如果沒有攜帶或者是僞造的就不允許訪問。

我們可以發現CSRF攻擊依靠的是cookie中所攜帶的認證信息。但是在前後端分離的項目中我們的認證信息其實是token,而token並不是存儲中cookie中,並且需要前端代碼去把token設置到請求頭中才可以,所以CSRF攻擊也就不用擔心了。

5、認證成功處理器

實際上在UsernamePasswordAuthenticationFilter進行登錄認證的時候,如果登錄成功了是會調用AuthenticationSuccessHandler的方法進行認證成功後的處理的。AuthenticationSuccessHandler就是登錄成功處理器。我們也可以自己去自定義成功處理器進行成功後的相應處理。

@Component
public class SGSuccessHandler implements AuthenticationSuccessHandler {

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        System.out.println("認證成功了");
    }
}
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private AuthenticationSuccessHandler successHandler;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin().successHandler(successHandler);

        http.authorizeRequests().anyRequest().authenticated();
    }
}

6、認證失敗處理器

實際上在UsernamePasswordAuthenticationFilter進行登錄認證的時候,如果認證失敗了是會調用AuthenticationFailureHandler的方法進行認證失敗後的處理的。AuthenticationFailureHandler就是登錄失敗處理器。

我們也可以自己去自定義失敗處理器進行失敗後的相應處理。

@Component
public class SGFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        System.out.println("認證失敗了");
    }
}
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private AuthenticationSuccessHandler successHandler;

    @Autowired
    private AuthenticationFailureHandler failureHandler;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin()
                //配置認證成功處理器
                .successHandler(successHandler)
                //配置認證失敗處理器
                .failureHandler(failureHandler);

        http.authorizeRequests().anyRequest().authenticated();
    }
}

7、登出成功處理器

@Component
public class SGLogoutSuccessHandler implements LogoutSuccessHandler {
    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        System.out.println("註銷成功");
    }
}
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private AuthenticationSuccessHandler successHandler;

    @Autowired
    private AuthenticationFailureHandler failureHandler;

    @Autowired
    private LogoutSuccessHandler logoutSuccessHandler;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin()
//                配置認證成功處理器
                .successHandler(successHandler)
//                配置認證失敗處理器
                .failureHandler(failureHandler);

        http.logout()
                //配置註銷成功處理器
                .logoutSuccessHandler(logoutSuccessHandler);

        http.authorizeRequests().anyRequest().authenticated();
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章