SSO Java example

1. Make sure you have reference for each of the imported libraries mentioned in the code in the file pom.xml
2. use this example of generating JWT and adjust it to suit your case.


import java.io.UnsupportedEncodingException;
import java.util.Date;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.view.RedirectView;
import javax.servlet.http.HttpServletRequest;

import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

public class SSOHandler {

// must define throw exception on function when using the getBytes("UTF-8") on the shared secret key
public RedirectView processRequest() throws UnsupportedEncodingException {

HttpServletRequest request = (
(ServletRequestAttributes) RequestContextHolder.getRequestAttributes()
).getRequest();

String sharedSecret = "shared_secret_key";

//The JWT signature algorithm we will be using to sign the token
SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;


// In java secret should be in utf-8 format or the generated jwt will be invalid
byte[] b = sharedSecret.getBytes("UTF-8");

long nowMillis = System.currentTimeMillis();

Date now = new Date(nowMillis);

String subject = "JohnDoe@sisense.com"; // should be supplied by the requester

JwtBuilder builder = Jwts.builder()
.setSubject(subject)
.setIssuedAt(now)
//.setAudience("sisense")
.setHeaderParam("typ", "JWT")
.signWith(signatureAlgorithm, b)
;

String jwt = builder.compact();

String return_to = "/app/main"; // any dashboard or widget to redirect the user after authentication. ((Optional))

String redirectUrl = "http://sisense.exampleWebsite.com:8111/jwt?jwt=" + jwt;// + "&return_to=" + return_to;

return new RedirectView(redirectUrl);
}
}