Java Code Examples for io.jsonwebtoken.Claims#getSubject()
The following examples show how to use
io.jsonwebtoken.Claims#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: TokenProvider.java From gpmr with Apache License 2.0 | 6 votes |
public Authentication getAuthentication(String token) { Claims claims = Jwts.parser() .setSigningKey(secretKey) .parseClaimsJws(token) .getBody(); Collection<? extends GrantedAuthority> authorities = Arrays.asList(claims.get(AUTHORITIES_KEY).toString().split(",")).stream() .map(SimpleGrantedAuthority::new) .collect(Collectors.toList()); User principal = new User(claims.getSubject(), "", authorities); return new UsernamePasswordAuthenticationToken(principal, "", authorities); }
Example 2
Source File: TokenAuthenticationHelper.java From spring-security-jwt-csrf with MIT License | 6 votes |
static Authentication getAuthentication(HttpServletRequest request) { Cookie cookie = WebUtils.getCookie(request, COOKIE_BEARER); String token = cookie != null ? cookie.getValue() : null; if (token != null) { Claims claims = Jwts.parser() .setSigningKey(SECRET) .parseClaimsJws(token) .getBody(); Collection<? extends GrantedAuthority> authorities = Arrays.stream(claims.get("authorities").toString().split(",")) .map(SimpleGrantedAuthority::new) .collect(Collectors.toList()); String userName = claims.getSubject(); return userName != null ? new UsernamePasswordAuthenticationToken(userName, null, authorities) : null; } return null; }
Example 3
Source File: TokenProvider.java From klask-io with GNU General Public License v3.0 | 6 votes |
public Authentication getAuthentication(String token) { Claims claims = Jwts.parser() .setSigningKey(secretKey) .parseClaimsJws(token) .getBody(); Collection<? extends GrantedAuthority> authorities = Arrays.asList(claims.get(AUTHORITIES_KEY).toString().split(",")).stream() .map(SimpleGrantedAuthority::new) .collect(Collectors.toList()); User principal = new User(claims.getSubject(), "", authorities); return new UsernamePasswordAuthenticationToken(principal, "", authorities); }
Example 4
Source File: JwtTokenAuthenticationFilter.java From scava with Eclipse Public License 2.0 | 6 votes |
@Override protected void doFilterInternal(HttpServletRequest req, HttpServletResponse rsp, FilterChain filterChain) throws ServletException, IOException { String token = req.getHeader(config.getHeader()); if (token != null && token.startsWith(config.getPrefix() + " ")) { token = token.replace(config.getPrefix() + " ", ""); try { Claims claims = Jwts.parser().setSigningKey(config.getSecret().getBytes()).parseClaimsJws(token) .getBody(); String username = claims.getSubject(); @SuppressWarnings("unchecked") List<String> authorities = claims.get("authorities", List.class); if (username != null) { UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(username, null, authorities.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList())); SecurityContextHolder.getContext().setAuthentication(auth); } } catch (Exception ignore) { SecurityContextHolder.clearContext(); } } filterChain.doFilter(req, rsp); }
Example 5
Source File: JwtAuthorizationHeaderFilter.java From training with MIT License | 6 votes |
@Override protected Object getPreAuthenticatedPrincipal(HttpServletRequest request) { String jwtHeader = request.getHeader(JWT_HEADER_NAME); if (jwtHeader == null) { return null; } String encodedJwt = jwtHeader; try { Claims claims = Jwts.parser() .setSigningKey(DatatypeConverter.parseBase64Binary(backendSecret)) .parseClaimsJws(encodedJwt) .getBody(); AuthnContext authnContext = getAuthnContext(claims); log.info("Attempting login with userid={} and level={}", claims.getSubject(), authnContext); return new UsernameContextPrincipal(claims.getSubject(), authnContext); } catch (UnsupportedJwtException jwtException) { throw new PreAuthenticatedCredentialsNotFoundException("Invalid JWT Token", jwtException); } }
Example 6
Source File: OAuthUtils.java From trellis with Apache License 2.0 | 6 votes |
/** * Generate a Principal from a subject claim. * @param claims the JWT claims * @return a Principal, if one can be generated from standard claims */ public static Principal withSubjectClaim(final Claims claims) { final String subject = claims.getSubject(); if (subject == null) return null; if (isUrl(subject)) { LOGGER.debug("Using JWT claim with sub: {}", subject); return new OAuthPrincipal(subject); } final String iss = claims.getIssuer(); // combine the iss and sub fields if that appears possible if (iss != null && isUrl(iss)) { final String webid = iss.endsWith("/") ? iss + subject : iss + "/" + subject; LOGGER.debug("Using JWT claim with generated webid: {}", webid); return new OAuthPrincipal(webid); } // Use an OIDC website claim, if one exists if (claims.containsKey(WEBSITE)) { final String site = claims.get(WEBSITE, String.class); LOGGER.debug("Using JWT claim with website: {}", site); return new OAuthPrincipal(site); } return null; }
Example 7
Source File: UserTokenRequiredAspect.java From Building-RESTful-Web-Services-with-Spring-5-Second-Edition with MIT License | 5 votes |
@Before("@annotation(userTokenRequired)") public void tokenRequiredWithAnnotation(UserTokenRequired userTokenRequired) throws Throwable{ ServletRequestAttributes reqAttributes = (ServletRequestAttributes)RequestContextHolder.currentRequestAttributes(); HttpServletRequest request = reqAttributes.getRequest(); // checks for token in request header String tokenInHeader = request.getHeader("token"); if(StringUtils.isEmpty(tokenInHeader)){ throw new IllegalArgumentException("Empty token"); } Claims claims = Jwts.parser() .setSigningKey(DatatypeConverter.parseBase64Binary(SecurityServiceImpl.secretKey)) .parseClaimsJws(tokenInHeader).getBody(); if(claims == null || claims.getSubject() == null){ throw new IllegalArgumentException("Token Error : Claim is null"); } String subject = claims.getSubject(); if(subject.split("=").length != 2){ throw new IllegalArgumentException("User token is not authorized"); } }
Example 8
Source File: JwtTokenAuthenticationFilter.java From scava with Eclipse Public License 2.0 | 5 votes |
@Override protected void doFilterInternal(HttpServletRequest req, HttpServletResponse rsp, FilterChain filterChain) throws ServletException, IOException { rsp.addHeader("Access-Control-Allow-Origin", "*"); rsp.addHeader("Access-Control-Allow-Headers", "Origin, Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers, Authorization"); rsp.addHeader("Access-Control-Expose-Headers", "Access-Control-Allow-Origin, Access-Control-Allow-Credentials, Authorization"); rsp.addHeader("Access-Control-Allow-Methods", "GET"); rsp.addHeader("Access-Control-Allow-Methods", "POST"); rsp.addHeader("Access-Control-Allow-Methods", "PUT"); rsp.addHeader("Access-Control-Allow-Methods", "DELETE"); String token = req.getHeader(config.getHeader()); if(req.getMethod().equals("OPTIONS")) { rsp.setStatus(HttpServletResponse.SC_OK); } else { if (token != null && token.startsWith(config.getPrefix() + " ")) { token = token.replace(config.getPrefix() + " ", ""); try { Claims claims = Jwts.parser().setSigningKey(config.getSecret().getBytes()).parseClaimsJws(token) .getBody(); String username = claims.getSubject(); @SuppressWarnings("unchecked") List<String> authorities = claims.get("authorities", List.class); if (username != null) { UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(username, null, authorities.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList())); SecurityContextHolder.getContext().setAuthentication(auth); } } catch (Exception ignore) { SecurityContextHolder.clearContext(); } } filterChain.doFilter(req, rsp); } }
Example 9
Source File: JwtTokenUtil.java From mall-tiny with Apache License 2.0 | 5 votes |
/** * 从token中获取登录用户名 */ public String getUserNameFromToken(String token) { String username; try { Claims claims = getClaimsFromToken(token); username = claims.getSubject(); } catch (Exception e) { username = null; } return username; }
Example 10
Source File: JwtTokenUtil.java From mall-learning with Apache License 2.0 | 5 votes |
/** * 从token中获取登录用户名 */ public String getUserNameFromToken(String token) { String username; try { Claims claims = getClaimsFromToken(token); username = claims.getSubject(); } catch (Exception e) { username = null; } return username; }
Example 11
Source File: JwtTokenUtil.java From xmanager with Apache License 2.0 | 5 votes |
public String getUsernameFromToken(String token) { String username; try { final Claims claims = getClaimsFromToken(token); username = claims.getSubject(); } catch (Exception e) { username = null; } return username; }
Example 12
Source File: SecurityServiceImpl.java From Building-RESTful-Web-Services-with-Spring-5-Second-Edition with MIT License | 5 votes |
@Override public String getSubject(String token) { Claims claims = Jwts.parser() .setSigningKey(DatatypeConverter.parseBase64Binary(secretKey)) .parseClaimsJws(token).getBody(); return claims.getSubject(); }
Example 13
Source File: JwtTokenFactory.java From Groza with Apache License 2.0 | 5 votes |
public SecurityUser parseAccessJwtToken(RawAccessJwtToken rawAccessToken) { Jws<Claims> jwsClaims = rawAccessToken.parseClaims(settings.getTokenSigningKey()); Claims claims = jwsClaims.getBody(); String subject = claims.getSubject(); List<String> scopes = claims.get(SCOPES, List.class); if (scopes == null || scopes.isEmpty()) { throw new IllegalArgumentException("JWT Token doesn't have any scopes"); } SecurityUser securityUser = new SecurityUser(new UserId(UUID.fromString(claims.get(USER_ID, String.class)))); securityUser.setEmail(subject); securityUser.setAuthority(Authority.parse(scopes.get(0))); securityUser.setFirstName(claims.get(FIRST_NAME, String.class)); securityUser.setLastName(claims.get(LAST_NAME, String.class)); securityUser.setEnabled(claims.get(ENABLED, Boolean.class)); boolean isPublic = claims.get(IS_PUBLIC, Boolean.class); UserPrincipal principal = new UserPrincipal(isPublic ? UserPrincipal.Type.PUBLIC_ID : UserPrincipal.Type.USER_NAME, subject); securityUser.setUserPrincipal(principal); String tenantId = claims.get(TENANT_ID, String.class); if (tenantId != null) { securityUser.setTenantId(new TenantId(UUID.fromString(tenantId))); } String customerId = claims.get(CUSTOMER_ID, String.class); if (customerId != null) { securityUser.setCustomerId(new CustomerId(UUID.fromString(customerId))); } return securityUser; }
Example 14
Source File: _JwtTokenUtil.java From generator-spring-rest-jwt with MIT License | 5 votes |
public String getUsernameFromToken(String token) { String username; try { final Claims claims = getClaimsFromToken(token); username = claims.getSubject(); } catch (Exception e) { username = null; } return username; }
Example 15
Source File: TokenAuthenticationHelper.java From SpringSecurity-JWT-Vue-Deom with MIT License | 5 votes |
/** * 对请求的验证 * */ public static Authentication getAuthentication(HttpServletRequest request) { Cookie cookie = WebUtils.getCookie(request, COOKIE_TOKEN); String token = cookie != null ? cookie.getValue() : null; if (token != null) { Claims claims = Jwts.parser() .setSigningKey(SECRET_KEY) .parseClaimsJws(token) .getBody(); // 获取用户权限 Collection<? extends GrantedAuthority> authorities = Arrays.stream(claims.get("authorities").toString().split(",")) .map(SimpleGrantedAuthority::new) .collect(Collectors.toList()); String userName = claims.getSubject(); if (userName != null) { UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(userName, null, authorities); usernamePasswordAuthenticationToken.setDetails(claims); return usernamePasswordAuthenticationToken; } return null; } return null; }
Example 16
Source File: TokenProvider.java From flair-engine with Apache License 2.0 | 5 votes |
public Authentication getAuthentication(String token) { Claims claims = Jwts.parser() .setSigningKey(secretKey) .parseClaimsJws(token) .getBody(); Collection<? extends GrantedAuthority> authorities = Arrays.stream(claims.get(AUTHORITIES_KEY).toString().split(",")) .map(SimpleGrantedAuthority::new) .collect(Collectors.toList()); User principal = new User(claims.getSubject(), "", authorities); return new UsernamePasswordAuthenticationToken(principal, token, authorities); }
Example 17
Source File: JwtTokenUtil.java From mall-learning with Apache License 2.0 | 5 votes |
/** * 从token中获取登录用户名 */ public String getUserNameFromToken(String token) { String username; try { Claims claims = getClaimsFromToken(token); username = claims.getSubject(); } catch (Exception e) { username = null; } return username; }
Example 18
Source File: JwtTokenUtil.java From SpringBootLearn with Apache License 2.0 | 5 votes |
/** * 根据token 获取用户名 * @param token * @return */ public String getUsernameFromToken(String token) { String username; try { final Claims claims = getClaimsFromToken(token); username = claims.getSubject(); } catch (Exception e) { username = null; } return username; }
Example 19
Source File: Crust.java From Milkomeda with MIT License | 4 votes |
/** * 根据请求令牌获取登录认证信息 * * @return Authentication */ Authentication getAuthenticationFromToken() { Authentication authentication = null; // 获取请求携带的令牌 String token = getToken(); if (token != null) { // 当前上下文认证信息不存在 if (getAuthentication() == null) { String unSignKey = getUnSignKey(); Claims claims = JwtUtil.parseToken(token, unSignKey); if (claims == null) { return null; } String username = claims.getSubject(); if (username == null) { return null; } if (JwtUtil.isTokenExpired(token, unSignKey)) { return null; } String uid = (String) claims.get(UID); long issuedAt = (long) claims.get(CREATED); long expire = claims.getExpiration().getTime(); // 设置Token元数据 CrustTokenMetaData tokenMetaData = new CrustTokenMetaData(username, uid, issuedAt, expire); tokenMetaDataThreadLocal.set(tokenMetaData); Object RoleIdsObj = claims.get(ROLE_IDS); List<Long> roleIds = null; if (RoleIdsObj != null) { roleIds = Arrays.stream(((String) RoleIdsObj).split(",")).map(Long::parseLong).collect(Collectors.toList()); } List<String> authoritiesList = getCrustUserDetailsService().findAuthorities(uid); List<GrantedAuthority> authorities = null; if (authoritiesList != null) { authorities = authoritiesList.stream().map(GrantedAuthorityImpl::new).collect(Collectors.toList()); } CrustUserDetails userDetails = new CrustUserDetails(uid, username, authorities, roleIds); authentication = new CrustAuthenticationToken(userDetails, null, authorities, token); } else { // 当前上下文认证信息存在,验证token是否正确匹配 if (validateToken(token, getUsername())) { // 如果上下文中Authentication非空,且请求令牌合法,直接返回当前登录认证信息 authentication = getAuthentication(); } } } return authentication; }
Example 20
Source File: JwtUtil.java From pre with GNU General Public License v3.0 | 2 votes |
/** * 从令牌中获取用户名 * * @param token 令牌 * @return 用户名 */ public static String getUsernameFromToken(String token) { Claims claims = getClaimsFromToken(token); return claims.getSubject(); }