package com.kidgrow.zuul.auth;
|
|
import org.springframework.security.authentication.ReactiveAuthenticationManager;
|
import org.springframework.security.core.Authentication;
|
import org.springframework.security.oauth2.common.OAuth2AccessToken;
|
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
|
import org.springframework.security.oauth2.provider.OAuth2Authentication;
|
import org.springframework.security.oauth2.provider.token.TokenStore;
|
import org.springframework.security.oauth2.server.resource.BearerTokenAuthenticationToken;
|
import reactor.core.publisher.Mono;
|
|
/**
|
* 石家庄喜高科技有限责任公司 版权所有 © Copyright 2020<br>
|
*
|
* @Description: <br>
|
* @Project: <br>
|
* @CreateDate: Created in 2020/2/22 22:44 <br>
|
* @Author: <a href="4345453@kidgrow.com">liuke</a>
|
*/
|
public class CustomAuthenticationManager implements ReactiveAuthenticationManager {
|
private TokenStore tokenStore;
|
|
public CustomAuthenticationManager(TokenStore tokenStore) {
|
this.tokenStore = tokenStore;
|
}
|
|
@Override
|
public Mono<Authentication> authenticate(Authentication authentication) {
|
return Mono.justOrEmpty(authentication)
|
.filter(a -> a instanceof BearerTokenAuthenticationToken)
|
.cast(BearerTokenAuthenticationToken.class)
|
.map(BearerTokenAuthenticationToken::getToken)
|
.flatMap((accessTokenValue -> {
|
OAuth2AccessToken accessToken = tokenStore.readAccessToken(accessTokenValue);
|
if (accessToken == null) {
|
return Mono.error(new InvalidTokenException("Invalid access token: " + accessTokenValue));
|
} else if (accessToken.isExpired()) {
|
tokenStore.removeAccessToken(accessToken);
|
return Mono.error(new InvalidTokenException("Access token expired: " + accessTokenValue));
|
}
|
|
OAuth2Authentication result = tokenStore.readAuthentication(accessToken);
|
if (result == null) {
|
return Mono.error(new InvalidTokenException("Invalid access token: " + accessTokenValue));
|
}
|
return Mono.just(result);
|
}))
|
.cast(Authentication.class);
|
}
|
}
|