登录与认证

private String createToken(User dbUser) {
    Map<String,Object> map = new HashMap<>();
    map.put("uid",dbUser.getId());
    map.put("name", dbUser.getName());
    return JWTUtil.createToken(map,"1234".getBytes());
}

前端解析jwt:

decodeJWT(jwt) {
    return JSON.parse(decodeURIComponent(window.atob(token.split(".")[1])))
}

网关jwt统一检查


@Component
public class JWTFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1. 哪些url需要进行安全检查
        String currentUrl = exchange.getRequest().getPath().value();
        if(!"/user/user/login".equals(currentUrl)) {
            MultiValueMap<String, HttpCookie> cookies = exchange.getRequest().getCookies();
            if(cookies != null && cookies.getFirst("token") != null) {
                HttpCookie token = cookies.getFirst("token");
                String jwt =  token.getValue();
                boolean verify = JWTUtil.verify(jwt, "1234".getBytes());
                if(!verify) {
                    return needLogin(exchange);
                }

            }else {
                return needLogin(exchange);
            }
        }
        //2, 对于需要安全检查的url进行检验。
        //3,合法通过,不合法拒绝。
        return chain.filter(exchange);
    }

    private Mono<Void> needLogin(ServerWebExchange exchange) {
        exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
        return exchange.getResponse().setComplete();
    }

    @Override
    public int getOrder() {
        return 0;
    }
}

Spring Security

基础表结构

create table users(
	username varchar_ignorecase(50) not null primary key,
	password varchar_ignorecase(50) not null,
	enabled boolean not null
);

create table authorities (
	username varchar_ignorecase(50) not null,
	authority varchar_ignorecase(50) not null,
	constraint fk_authorities_users foreign key(username) references users(username)
);
create unique index ix_auth_username on authorities (username,authority);

create table persistent_logins (
	username varchar(64) not null,
	series varchar(64) primary key,
	token varchar(64) not null,
	last_used timestamp not null
);