use of com.nimbusds.jwt.SignedJWT in project SEPA by arces-wot.
the class AuthorizationManager method getToken.
/**
* POST https://wot.arces.unibo.it:8443/oauth/token
*
* Content-Type: application/x-www-form-urlencoded
* Accept: application/json
* Authorization: Basic Basic64(id:secret)
*
* Response example:
* { "access_token": "eyJraWQiOiIyN.........",
* "token_type": "bearer",
* "expires_in": 3600
* }
*
* In case of error, the following applies:
* {
* "code": Error code,
* "body": "Error details"
*
* }
*/
public Response getToken(String encodedCredentials) {
logger.debug("Get token");
// Decode credentials
byte[] decoded = null;
try {
decoded = Base64.getDecoder().decode(encodedCredentials);
} catch (IllegalArgumentException e) {
logger.error("Not authorized");
return new ErrorResponse(0, HttpStatus.SC_UNAUTHORIZED, "Client not authorized");
}
String decodedCredentials = new String(decoded);
String[] clientID = decodedCredentials.split(":");
if (clientID == null) {
logger.error("Wrong Basic authorization");
return new ErrorResponse(0, HttpStatus.SC_UNAUTHORIZED, "Client not authorized");
}
if (clientID.length != 2) {
logger.error("Wrong Basic authorization");
return new ErrorResponse(0, HttpStatus.SC_UNAUTHORIZED, "Client not authorized");
}
String id = decodedCredentials.split(":")[0];
String secret = decodedCredentials.split(":")[1];
logger.debug("Credentials: " + id + " " + secret);
// Verify credentials
if (!credentials.containsKey(id)) {
logger.error("Client id: " + id + " is not registered");
return new ErrorResponse(0, HttpStatus.SC_UNAUTHORIZED, "Client not authorized");
}
if (!credentials.get(id).equals(secret)) {
logger.error("Wrong secret: " + secret + " for client id: " + id);
return new ErrorResponse(0, HttpStatus.SC_UNAUTHORIZED, "Client not authorized");
}
// Check is a token has been release for this client
if (clientClaims.containsKey(id)) {
// Do not return a new token if the previous one is not expired
Date expires = clientClaims.get(id).getExpirationTime();
Date now = new Date();
logger.debug("Check token expiration: " + now + " > " + expires + " ?");
if (now.before(expires)) {
logger.warn("Token is not expired");
return new ErrorResponse(0, HttpStatus.SC_BAD_REQUEST, "Token is not expired");
}
}
// Prepare JWT with claims set
JWTClaimsSet.Builder claimsSetBuilder = new JWTClaimsSet.Builder();
long timestamp = new Date().getTime();
/*
* 4.1.1. "iss" (Issuer) Claim
The "iss" (issuer) claim identifies the principal that issued the
JWT. The processing of this claim is generally application specific.
The "iss" value is a case-sensitive string containing a StringOrURI
value. Use of this claim is OPTIONAL.*/
claimsSetBuilder.issuer(AuthorizationManagerBeans.getIssuer());
/* 4.1.2. "sub" (Subject) Claim
The "sub" (subject) claim identifies the principal that is the
subject of the JWT. The Claims in a JWT are normally statements
about the subject. The subject value MUST either be scoped to be
locally unique in the context of the issuer or be globally unique.
The processing of this claim is generally application specific. The
"sub" value is a case-sensitive string containing a StringOrURI
value. Use of this claim is OPTIONAL.*/
claimsSetBuilder.subject(AuthorizationManagerBeans.getSubject());
/* 4.1.3. "aud" (Audience) Claim
The "aud" (audience) claim identifies the recipients that the JWT is
intended for. Each principal intended to process the JWT MUST
identify itself with a value in the audience claim. If the principal
processing the claim does not identify itself with a value in the
"aud" claim when this claim is present, then the JWT MUST be
rejected. In the general case, the "aud" value is an array of case-
sensitive strings, each containing a StringOrURI value. In the
special case when the JWT has one audience, the "aud" value MAY be a
single case-sensitive string containing a StringOrURI value. The
interpretation of audience values is generally application specific.
Use of this claim is OPTIONAL.*/
ArrayList<String> audience = new ArrayList<String>();
audience.add(AuthorizationManagerBeans.getHttpsAudience());
audience.add(AuthorizationManagerBeans.getWssAudience());
claimsSetBuilder.audience(audience);
/* 4.1.4. "exp" (Expiration Time) Claim
The "exp" (expiration time) claim identifies the expiration time on
or after which the JWT MUST NOT be accepted for processing. The
processing of the "exp" claim requires that the current date/time
MUST be before the expiration date/time listed in the "exp" claim.
Implementers MAY provide for some small leeway, usually no more than
a few minutes, to account for clock skew. Its value MUST be a number
containing a NumericDate value. Use of this claim is OPTIONAL.*/
claimsSetBuilder.expirationTime(new Date(timestamp + (AuthorizationManagerBeans.getTokenExpiringPeriod() * 1000)));
/*4.1.5. "nbf" (Not Before) Claim
The "nbf" (not before) claim identifies the time before which the JWT
MUST NOT be accepted for processing. The processing of the "nbf"
claim requires that the current date/time MUST be after or equal to
the not-before date/time listed in the "nbf" claim. Implementers MAY
provide for some small leeway, usually no more than a few minutes, to
account for clock skew. Its value MUST be a number containing a
NumericDate value. Use of this claim is OPTIONAL.*/
claimsSetBuilder.notBeforeTime(new Date(timestamp - 1000));
/* 4.1.6. "iat" (Issued At) Claim
The "iat" (issued at) claim identifies the time at which the JWT was
issued. This claim can be used to determine the age of the JWT. Its
value MUST be a number containing a NumericDate value. Use of this
claim is OPTIONAL.*/
claimsSetBuilder.issueTime(new Date(timestamp));
/*4.1.7. "jti" (JWT ID) Claim
The "jti" (JWT ID) claim provides a unique identifier for the JWT.
The identifier value MUST be assigned in a manner that ensures that
there is a negligible probability that the same value will be
accidentally assigned to a different data object; if the application
uses multiple issuers, collisions MUST be prevented among values
produced by different issuers as well. The "jti" claim can be used
to prevent the JWT from being replayed. The "jti" value is a case-
sensitive string. Use of this claim is OPTIONAL.*/
claimsSetBuilder.jwtID(id + ":" + secret);
JWTClaimsSet jwtClaims = claimsSetBuilder.build();
// ******************************
// Sign JWT with private RSA key
// ******************************
SignedJWT signedJWT;
try {
signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.RS256), JWTClaimsSet.parse(jwtClaims.toString()));
} catch (ParseException e) {
logger.error(e.getMessage());
return new ErrorResponse(0, HttpStatus.SC_INTERNAL_SERVER_ERROR, "Error on signing JWT (1)");
}
try {
signedJWT.sign(signer);
} catch (JOSEException e) {
logger.error(e.getMessage());
return new ErrorResponse(0, HttpStatus.SC_INTERNAL_SERVER_ERROR, "Error on signing JWT (2)");
}
// Add the token to the released tokens
clientClaims.put(id, jwtClaims);
return new JWTResponse(signedJWT.serialize(), "bearer", AuthorizationManagerBeans.getTokenExpiringPeriod());
}
use of com.nimbusds.jwt.SignedJWT in project ranger by apache.
the class RangerSSOAuthenticationFilter method doFilter.
/*
* doFilter of RangerSSOAuthenticationFilter is the first in the filter list so in this it check for the request
* if the request is from browser, doesn't contain local login and sso is enabled then it process the request against knox sso
* else if it's ssoenable and the request is with local login string then it show's the appropriate msg
* else if ssoenable is false then it contiunes with further filters as it was before sso
*/
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
String xForwardedURL = constructForwardableURL(httpRequest);
if (httpRequest.getRequestedSessionId() != null && !httpRequest.isRequestedSessionIdValid()) {
synchronized (httpRequest.getServletContext()) {
if (httpRequest.getServletContext().getAttribute(httpRequest.getRequestedSessionId()) != null && "locallogin".equals(httpRequest.getServletContext().getAttribute(httpRequest.getRequestedSessionId()).toString())) {
httpRequest.getSession().setAttribute("locallogin", "true");
httpRequest.getServletContext().removeAttribute(httpRequest.getRequestedSessionId());
}
}
}
RangerSecurityContext context = RangerContextHolder.getSecurityContext();
UserSessionBase session = context != null ? context.getUserSession() : null;
boolean ssoEnabled = session != null ? session.isSSOEnabled() : PropertiesUtil.getBooleanProperty("ranger.sso.enabled", false);
String userAgent = httpRequest.getHeader("User-Agent");
if (httpRequest.getSession() != null) {
if (httpRequest.getSession().getAttribute("locallogin") != null) {
servletRequest.setAttribute("ssoEnabled", false);
filterChain.doFilter(servletRequest, servletResponse);
return;
}
}
// If sso is enable and request is not for local login and is from browser then it will go inside and try for knox sso authentication
if (ssoEnabled && !httpRequest.getRequestURI().contains(LOCAL_LOGIN_URL)) {
// Note : Need to remove !isAuthenticated() after knoxsso solve the bug from cross-origin script
if (jwtProperties != null && !isAuthenticated()) {
HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
String serializedJWT = getJWTFromCookie(httpRequest);
// if we get the hadoop-jwt token from the cookies then will process it further
if (serializedJWT != null) {
SignedJWT jwtToken = null;
try {
jwtToken = SignedJWT.parse(serializedJWT);
boolean valid = validateToken(jwtToken);
// if the public key provide is correct and also token is not expired the process token
if (valid) {
String userName = jwtToken.getJWTClaimsSet().getSubject();
LOG.info("SSO login user : " + userName);
String rangerLdapDefaultRole = PropertiesUtil.getProperty("ranger.ldap.default.role", "ROLE_USER");
// if we get the userName from the token then log into ranger using the same user
if (userName != null && !userName.trim().isEmpty()) {
final List<GrantedAuthority> grantedAuths = new ArrayList<>();
grantedAuths.add(new SimpleGrantedAuthority(rangerLdapDefaultRole));
final UserDetails principal = new User(userName, "", grantedAuths);
final Authentication finalAuthentication = new UsernamePasswordAuthenticationToken(principal, "", grantedAuths);
WebAuthenticationDetails webDetails = new WebAuthenticationDetails(httpRequest);
((AbstractAuthenticationToken) finalAuthentication).setDetails(webDetails);
RangerAuthenticationProvider authenticationProvider = new RangerAuthenticationProvider();
authenticationProvider.setSsoEnabled(ssoEnabled);
Authentication authentication = authenticationProvider.authenticate(finalAuthentication);
authentication = getGrantedAuthority(authentication);
SecurityContextHolder.getContext().setAuthentication(authentication);
}
filterChain.doFilter(servletRequest, httpServletResponse);
} else // if the token is not valid then redirect to knox sso
{
if (isWebUserAgent(userAgent)) {
String ssourl = constructLoginURL(httpRequest, xForwardedURL);
if (LOG.isDebugEnabled()) {
LOG.debug("SSO URL = " + ssourl);
}
httpServletResponse.sendRedirect(ssourl);
} else {
filterChain.doFilter(servletRequest, httpServletResponse);
}
}
} catch (ParseException e) {
LOG.warn("Unable to parse the JWT token", e);
}
} else // if the jwt token is not available then redirect it to knox sso
{
if (isWebUserAgent(userAgent)) {
String ssourl = constructLoginURL(httpRequest, xForwardedURL);
if (LOG.isDebugEnabled()) {
LOG.debug("SSO URL = " + ssourl);
}
httpServletResponse.sendRedirect(ssourl);
} else {
filterChain.doFilter(servletRequest, httpServletResponse);
}
}
} else // if property is not loaded or is already authenticated then proceed further with next filter
{
filterChain.doFilter(servletRequest, servletResponse);
}
} else if (ssoEnabled && ((HttpServletRequest) servletRequest).getRequestURI().contains(LOCAL_LOGIN_URL) && isWebUserAgent(userAgent) && isAuthenticated()) {
// If already there's an active session with sso and user want's to switch to local login(i.e without sso) then it won't be navigated to local login
// In this scenario the user as to use separate browser
String url = ((HttpServletRequest) servletRequest).getRequestURI().replace(LOCAL_LOGIN_URL + "/", "");
url = url.replace(LOCAL_LOGIN_URL, "");
LOG.warn("There is an active session and if you want local login to ranger, try this on a separate browser");
((HttpServletResponse) servletResponse).sendRedirect(url);
} else // if sso is not enable or the request is not from browser then proceed further with next filter
{
filterChain.doFilter(servletRequest, servletResponse);
}
}
use of com.nimbusds.jwt.SignedJWT in project perry by ca-cwds.
the class JwtService method generate.
public String generate(String id, String subject, Map<String, String> customJwtClaimsMap) {
try {
JWTClaimsSet claimsSet = prepareClaims(id, subject, customJwtClaimsMap);
SignedJWT signedJWT = sign(claimsSet);
String token;
if (configuration.isEncryptionEnabled()) {
JWEObject jweObject = encrypt(signedJWT);
token = jweObject.serialize();
} else {
token = signedJWT.serialize();
}
return removeHeader(token);
} catch (Exception e) {
throw new JwtException(e);
}
}
use of com.nimbusds.jwt.SignedJWT in project perry by ca-cwds.
the class JwtService method validate.
public String validate(String token) throws JwtException {
try {
String tokenWithHeader = addHeader(token);
SignedJWT signedJWT;
if (configuration.isEncryptionEnabled()) {
signedJWT = decrypt(tokenWithHeader);
} else {
signedJWT = SignedJWT.parse(tokenWithHeader);
}
validateSignature(signedJWT);
JWTClaimsSet claimsSet = signedJWT.getJWTClaimsSet();
validateClaims(claimsSet);
return claimsSet.getStringClaim(IDENTITY_CLAIM);
} catch (Exception e) {
throw new JwtException(e);
}
}
use of com.nimbusds.jwt.SignedJWT in project ratauth by alfa-laboratory.
the class HS256TokenProcessor method createToken.
@Override
@SneakyThrows
public String createToken(String clientId, String secret, String identifier, Date created, Date expiresIn, Set<String> audience, Set<String> scopes, Collection<String> authContext, String userId, Map<String, Object> userInfo) {
final JWSSigner signer = new MACSigner(Base64.getDecoder().decode(secret));
final List<String> aud = new ArrayList<>(audience);
aud.add(clientId);
// Prepare JWT with claims set
JWTClaimsSet.Builder jwtBuilder = new JWTClaimsSet.Builder().issuer(issuer).subject(userId).expirationTime(expiresIn).audience(aud).claim(SCOPE, scopes).claim(CLIENT_ID, clientId).claim(ACR_VALUES, authContext).jwtID(identifier).issueTime(created);
userInfo.forEach(jwtBuilder::claim);
SignedJWT signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.HS256), jwtBuilder.build());
// Apply the HMAC protection
signedJWT.sign(signer);
// eyJhbGciOiJIUzI1NiJ9.SGVsbG8sIHdvcmxkIQ.onO9Ihudz3WkiauDO2Uhyuz0Y18UASXlSc1eS0NkWyA
return signedJWT.serialize();
}
Aggregations