Java Code Examples for com.auth0.jwt.interfaces.DecodedJWT#getSubject()

The following examples show how to use com.auth0.jwt.interfaces.DecodedJWT#getSubject() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JwtAuthenticationServiceImpl.java    From alibaba-rsocket-broker with Apache License 2.0 6 votes vote down vote up
@Override
public @Nullable NamedPrincipal auth(String jwtToken) {
    int tokenHashCode = jwtToken.hashCode();
    NamedPrincipal principal = jwtVerifyCache.getIfPresent(tokenHashCode);
    if (principal == null) {
        for (JWTVerifier verifier : verifiers) {
            try {
                DecodedJWT decodedJWT = verifier.verify(jwtToken);
                principal = new NamedPrincipal(decodedJWT.getSubject());
                jwtVerifyCache.put(tokenHashCode, principal);
                break;
            } catch (JWTVerificationException ignore) {

            }
        }
    }
    return principal;
}
 
Example 2
Source File: JwtApplication.java    From spring-boot-study with MIT License 6 votes vote down vote up
/**
 * 验证 token
 * */
private static void verifyJWTToken(String token) throws JWTVerificationException {
    Algorithm algorithm=Algorithm.HMAC256("secret");
    JWTVerifier verifier = JWT.require(algorithm)
            .withIssuer("SERVICE")
            .build();

    DecodedJWT jwt =verifier.verify(token);
    String subject=jwt.getSubject();
    Map<String,Claim> claims=jwt.getClaims();
    Claim claim = claims.get("loginName");
    System.out.println("自定义 claim:"+claim.asString());

    List<String> audience = jwt.getAudience();
    System.out.println("subject 值:"+subject);
    System.out.println("audience 值:"+audience.get(0));
}
 
Example 3
Source File: SonosHelper.java    From airsonic-advanced with GNU General Public License v3.0 5 votes vote down vote up
public Pair<SonosLink, String> getSonosLinkFromJWT(String jwt) {
    DecodedJWT djwt = JWTSecurityService.decode(jwt); // does NOT verify!
    SonosLink sl = new SonosLink(djwt.getSubject(),
            djwt.getClaim(SonosLinkSecurityInterceptor.CLAIM_LINKCODE).asString(),
            djwt.getClaim(SonosLinkSecurityInterceptor.CLAIM_HOUSEHOLDID).asString(),
            null, null);
    return Pair.of(sl, djwt.getClaim(SonosLinkSecurityInterceptor.CLAIM_REFRESH_TOKEN).asString());
}
 
Example 4
Source File: SessionSubject.java    From keeper with Apache License 2.0 5 votes vote down vote up
private String getUsername(String token) {
    if (StringUtil.isEmpty(token)) {
        return null;
    }
    SessionConfig config = sessionConfig();
    try {
        JWTVerifier verifier = JWT.require(
                Algorithm.HMAC256(config.getSecret()))
                .build();

        DecodedJWT jwt = verifier.verify(token);
        return jwt.getSubject();
    } catch (Exception e) {
        return null;
    }
}
 
Example 5
Source File: JwtPrincipal.java    From alibaba-rsocket-broker with Apache License 2.0 5 votes vote down vote up
public JwtPrincipal(DecodedJWT decodedJWT, String credentials) {
    this.hashcode = MurmurHash3.hash32(credentials);
    this.subject = decodedJWT.getSubject();
    this.audience = decodedJWT.getAudience();
    Map<String, Claim> claims = decodedJWT.getClaims();
    this.serviceAccounts = new HashSet<>(decodedJWT.getClaim("sas").asList(String.class));
    this.organizations = new HashSet<>(decodedJWT.getClaim("orgs").asList(String.class));
    if (claims.containsKey("roles")) {
        this.roles = new HashSet<>(decodedJWT.getClaim("roles").asList(String.class));
    }
    if (claims.containsKey("authorities")) {
        this.authorities = new HashSet<>(decodedJWT.getClaim("authorities").asList(String.class));
    }
}
 
Example 6
Source File: JwtUtil.java    From fastdep with Apache License 2.0 5 votes vote down vote up
/**
 * get user id
 *
 * @return user id
 */
public String getUserId() {
    try {
        DecodedJWT jwt = JWT.decode(getSubject().getPrincipal().toString());
        return jwt.getSubject();
    } catch (Exception e) {
        return null;
    }
}
 
Example 7
Source File: JwtUtil.java    From fastdep with Apache License 2.0 5 votes vote down vote up
/**
 * get user id
 *
 * @param token jwt token
 * @return user id
 */
public String getUserId(String token) {
    try {
        DecodedJWT jwt = JWT.decode(token);
        return jwt.getSubject();
    } catch (Exception e) {
        return null;
    }
}
 
Example 8
Source File: Token.java    From mdw with Apache License 2.0 5 votes vote down vote up
private void verify() throws IOException {
    Props props = new Props(this);

    String mdwAppId = appId;
    if (mdwAppId == null)
        mdwAppId = props.get(Props.APP_ID);
    if (mdwAppId == null)
        throw new IOException("--app-id param or mdw.app.id prop required");

    if (userToken == null)
        throw new IOException("--user-token required for verification");

    String mdwAppToken = appToken;
    if (mdwAppToken == null)
        mdwAppToken = System.getenv("MDW_APP_TOKEN");
    if (mdwAppToken == null)
        throw new IOException("--app-token param or MDW_APP_TOKEN environment variable required");

    JWTVerifier verifier = JWT.require(Algorithm.HMAC256(mdwAppToken))
            .withIssuer("mdwAuth")
            .withAudience(mdwAppId)
            .build();

    DecodedJWT jwt = verifier.verify(userToken);
    String subject = jwt.getSubject();
    getOut().println("Token verified for app " + mdwAppId + " and user " + subject);
}
 
Example 9
Source File: AuthController.java    From tutorials with MIT License 5 votes vote down vote up
@GetMapping(value="/callback")
public void callback(HttpServletRequest request, HttpServletResponse response) throws IOException, IdentityVerificationException {
    Tokens tokens = authenticationController.handle(request, response);

    DecodedJWT jwt = JWT.decode(tokens.getIdToken());
    TestingAuthenticationToken authToken2 = new TestingAuthenticationToken(jwt.getSubject(), jwt.getToken());
    authToken2.setAuthenticated(true);

    SecurityContextHolder.getContext().setAuthentication(authToken2);
    response.sendRedirect(config.getContextPath(request) + "/"); 
}
 
Example 10
Source File: JWTAuthentication.java    From codeway_service with GNU General Public License v3.0 4 votes vote down vote up
/**
 * 解析JWT,获取claims
 * @param jwtStr:待解密的jwt
 * @return String
 */
public static User parseJwtToSubject(String jwtStr)  {
	DecodedJWT jwt = parse(jwtStr);
	String subject = jwt.getSubject();
	return JsonUtil.jsonToPojo(subject,User.class);
}
 
Example 11
Source File: TokenAuthenticationProvider.java    From ChengFeng1.5 with MIT License 4 votes vote down vote up
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {

	DecodedJWT jwt = ((UserToken)authentication).getToken();



	boolean expire=jwt.getExpiresAt().before(new Date());

	if(expire)
		throw new TokenException("Token 已经失效");

	String username = jwt.getSubject();

	UserDetails user = userService.getUserLoginInfo(username);

	if(user == null || user.getPassword()==null)
		throw new TokenException("Token 已经失效");
	String encryptSalt = user.getPassword();
	try {
           Algorithm algorithm = Algorithm.HMAC256(encryptSalt);
           JWTVerifier verifier = JWT.require(algorithm)
                   .withSubject(username)
                   .build();
           verifier.verify(jwt.getToken());
       } catch (Exception e) {
           throw new BadCredentialsException("Token 认证失败", e);
       }
	UserToken token = new UserToken(user, jwt, user.getAuthorities());

	return token;
}
 
Example 12
Source File: JWTAuthentication.java    From codeway_service with GNU General Public License v3.0 4 votes vote down vote up
/**
 * 解析JWT,获取claims
 * @param jwtStr:待解密的jwt
 * @return String
 */
public static User parseJwtToSubject(String jwtStr)  {
	DecodedJWT jwt = parse(jwtStr);
	String subject = jwt.getSubject();
	return JsonUtil.jsonToPojo(subject,User.class);
}
 
Example 13
Source File: TokenUtil.java    From BlogManagePlatform with Apache License 2.0 2 votes vote down vote up
/**
 * 验证token
 * @author Frodez
 * @param token
 * @date 2018-11-21
 */
public static UserDetails verify(String token) {
	//前面已经将exp置为合适的过期时间了,这里只需要判断其是否超过当前时间即可.
	DecodedJWT jwt = expired ? expiredVerifier.verify(token) : verifier.verify(token);
	return new User(jwt.getSubject(), "N/A", AuthorityUtil.make(jwt.getClaim(authorityClaim).asArray(String.class)));
}
 
Example 14
Source File: TokenUtil.java    From BlogManagePlatform with Apache License 2.0 2 votes vote down vote up
/**
 * 验证token,且一定考虑过期
 * @author Frodez
 * @date 2018-11-21
 */
public static UserDetails verifyWithNoExpired(String token) {
	DecodedJWT jwt = verifier.verify(token);
	return new User(jwt.getSubject(), "N/A", AuthorityUtil.make(jwt.getClaim(authorityClaim).asArray(String.class)));
}