标签: 舟哥的Spring Boot手册

  • 舟哥的Spring Boot手册:Spring Security入门

    舟哥的Spring Boot手册

    目的

    • 旨在记录Spring Boot的经验
    • 从零到一构建WEB项目
    • 纯API服务

    资源

    • 基于Spring Boot 2.0构建
    • 推荐使用JetBrains IDEA编辑器

    完成度

    • [x] Spring Security
    • [x] Spring JPA

    简单介绍一下Spring Security

    Spring Security是Spring全家桶中负责安全的模块,安全是任何一个应用访问的基础。在我经验中安全主要提供两个主要功能,一个是Authentication,另外一个是Authorization。

    Authentication的意思是鉴权,也就是通过请求判断用户身份,传统的手段很多,比如表单登陆,Basic Auth,令牌等等。Authorization就是访问控制,用来控制应用内的ACL(Access Control List,访问控制列表),由此判断当前用户是否有权限来使用对应资源。

    Spring Security的设计初衷是所有应用都能使用安全模块,但毫无疑问作为全家桶成员,他在WEB方面是有很多天生优势的,和很多安全系统设计Shiro,Symfony Securiy等是高度相似的,如果有这些产品的经验,会很容易的转换到Spring Security中去。

    JWT概念

    概述

    JWT(JSON Web Token),是JWT组织提出的一种基于JSON在客户端和服务器之间交换用户态的一种规范。

    优点

    • 天生WEB亲和力
    • 不再使用Session,降低服务器性能开销。
    • 使用方便,全平台类库很容易找到。
    • 基于JWT可以衍生出很多安全策略

    微信登陆流程

    所有OPENID登陆基类

    package com.nuspet.yihuan.security.mini;
    
    import org.springframework.security.authentication.AbstractAuthenticationToken;
    
    // 小程序系列的token接口
    // 衍生出微信,百度,支付宝等小程序token的类
    public abstract class OpenIDToken extends AbstractAuthenticationToken {
    
        // 构造函数的说
        // 小程序类型的登陆token没有权限
        public OpenIDToken() {
            super(null);
            super.setAuthenticated(false);
        }
    
        // 小程序token都会转换成jwt token 所以不能设置信任为ture
        @Override
        public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {
            if (isAuthenticated) {
                throw new IllegalArgumentException(
                        "不能设置小程序类token受信任,最终会转换成信任的jwt token。");
            }
            super.setAuthenticated(false);
        }
    }