I have developed an application which do SSO in various applications. I am able to authorize user and able to redirect on application embedded link by passing sessionToken which is a value of cookieToken in that url and this piece of code is working fine and not asking for login again.
#GetMapping("get-sso-url/{user_id}")
public ResponseEntity<Object> getSSOUrl(#PathVariable("user_id") String userId, #RequestParam("app_id") String appId){
log.info("DashboardController::getSSOUrl::START");
UserActivityDetails userActivityDetails = userActivityService.getUserActivity(userId);
AppInfoDetails appInfoDetails = appInfoService.findById(appId);
String appUrl = appInfoDetails.getApiEndpoint() + userActivityDetails.getCookieToken();
log.debug("DashboardController::getSSOUrl::appUrl " + appUrl);
log.info("DashboardController::getSSOUrl::END");
return new ResponseEntity<>(new UrlResponse(appUrl), HttpStatus.OK);
}
Now I just want to verify that the url is returning HttpStatus.OK or not? so I have written like this:
public ResponseEntity<Object> getSSOUrl(#PathVariable("user_id") String userId, #RequestParam("app_id") String appId){
log.info("DashboardController::getSSOUrl::START");
UserActivityDetails userActivityDetails = userActivityService.getUserActivity(userId);
AppInfoDetails appInfoDetails = appInfoService.findById(appId);
String appUrl = appInfoDetails.getApiEndpoint() + userActivityDetails.getCookieToken();
log.debug("DashboardController::getSSOUrl::appUrl " + appUrl);
log.info("DashboardController::getSSOUrl::END");
return checkAppResponse(appUrl).equals(HttpStatus.OK) ? new ResponseEntity<>(new UrlResponse(appUrl), HttpStatus.OK)
: new ResponseEntity<>(new UrlResponse(appUrl), HttpStatus.NOT_FOUND);
}
private HttpStatus checkAppResponse(String appUrl){
try{
URL url = new URL(appUrl);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
int statusCode = httpURLConnection.getResponseCode();
if(statusCode == 200)
return HttpStatus.OK;
} catch (MalformedURLException e) {
throw new CustomRuntimeException(e.getMessage());
} catch (IOException e) {
throw new RuntimeException(e);
}
return HttpStatus.NOT_FOUND;
}
After adding above check, when I'm trying to redirect on application it asks me to login to the okta first.
Here is a sreenshot
Related
I am new to the Okta SSO, trying to get the Access token using below code.Am i using right API and package to do this? Please suggest, Thanks in advance
private com.microsoft.aad.adal4j.AuthenticationResult.AuthenticationResult getAccessToken(
AuthorizationCode authorizationCode, String currentUri)
throws Throwable {
String authCode = authorizationCode.getValue();
ClientCredential credential = new ClientCredential(clientId,
clientSecret);
com.microsoft.aad.adal4j.AuthenticationContext context = null;
com.microsoft.aad.adal4j.AuthenticationResult result = null;
java.util.concurrent.ExecutorService service = null;
try {
service = Executors.newFixedThreadPool(1);
context = new AuthenticationContext("https://dev-xxxxxxx.okta.com/oauth2/oauth2/authorize", true,
service);
Future<AuthenticationResult> future = context.acquireTokenByAuthorizationCode(authCode, new URI(currentUri), credential, null);
result = future.get();
} catch (ExecutionException e) {
throw e.getCause();
} catch(InterruptedException e){
LOGGER.error(e);
} catch(MalformedURLException e){
LOGGER.error("Malformed URL :"+e);
}finally {
service.shutdown();
}
if (result == null) {
throw new ServiceUnavailableException(
"authentication result was null");
}
return result;
}
10:59:05,653 ERROR AuthenticationContext:148 - [Correlation ID: cc2fccef-6c3c-4638-ae53-02d8ac2504c7] Request to acquire token failed.
java.io.FileNotFoundException: https://xxxxxx/common/discovery/instance?api-version=1.0&authorization_endpoint=https://xxxxxxxx/oauth2/oauth2/authorize
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1872)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1474)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254)
at com.microsoft.aad.adal4j.HttpHelper.readResponseFromConnection(HttpHelper.java:86)
at com.microsoft.aad.adal4j.HttpHelper.getResponse(HttpHelper.java:182)
at com.microsoft.aad.adal4j.HttpHelper.executeGetRequest(HttpHelper.java:158)
at com.microsoft.aad.adal4j.HttpHelper.executeHttpGet(HttpHelper.java:59)
at com.microsoft.aad.adal4j.AuthenticationAuthority.doDynamicInstanceDiscovery(AuthenticationAuthority.java:149)
at com.microsoft.aad.adal4j.AuthenticationAuthority.doInstanceDiscovery(AuthenticationAuthority.java:135)
at com.microsoft.aad.adal4j.AuthenticationContext.acquireTokenCommon(AuthenticationContext.java:775)
at com.microsoft.aad.adal4j.AuthenticationContext.access$100(AuthenticationContext.java:64)
at com.microsoft.aad.adal4j.AuthenticationContext$1.call(AuthenticationContext.java:141)
at com.microsoft.aad.adal4j.AuthenticationContext$1.call(AuthenticationContext.java:130)
I trying to include response from other url from ResponseEntity for oauth authorization but it is failing as I am unable to specify request method.
Below is the code
#RequestMapping(value = "/login/otp", method = RequestMethod.POST, produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
#ResponseBody
public ResponseEntity<?> getOTP(#Valid #RequestBody String loginDtls,UriComponentsBuilder ucBuilder) {
LoginDAO login = null;
ResponseEntity<?> resp = null;
try {
ObjectMapper mapper = new ObjectMapper();
String userId = "";
try {
JsonNode root = mapper.readTree(loginDtls);
userId = root.get("userId").textValue();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("UserController : getting otp for contact "+ userId);
login = loginService.findByUserId(userId);
if (login==null) {
System.out.println("A UserDAO with name " + userId + " does not exist");
resp = new ResponseEntity<String>(HttpStatus.NOT_FOUND);
}
String otp = GenUtil.generateOTP();
LoginDAO loginUpd = new LoginDAO(login);
loginUpd.setOtp(otp);
loginUpd.setOtpTimestamp(new Timestamp(System.currentTimeMillis()));
loginService.updateLogin(loginUpd);
System.out.println(loginUpd);
resp = getAuthenticated(ucBuilder);
System.out.println(resp.getStatusCodeValue());
System.out.println(resp.getBody());
}catch(Exception e) {
e.printStackTrace();
}
resp = new ResponseEntity<String>(login.toString(), HttpStatus.OK);
return resp;
}
private ResponseEntity<?> getAuthenticated(UriComponentsBuilder ucBuilder){
HttpHeaders headers = new HttpHeaders();
URI uri= ucBuilder.path("/oauth/token"+PASSWORD_GRANT).build().toUri();
List<MediaType> accept = new ArrayList<MediaType>();
accept.add(MediaType.APPLICATION_JSON_UTF8);
headers.setAccept(accept);
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
headers.setBasicAuth("my-trusted-client", "secret");
System.out.println(headers);
ResponseEntity<?> resp = ResponseEntity.created(uri).headers(headers).build();
return resp;
}
I have this error when I try to generate the token.
I have do this tutorial http://blog.xebia.in/index.php/2017/12/21/spring-security-and-oauth2-with-azure-active-directory/.
My problem is when I try to get an access token after I have the code.
I have this error:
Here is the related code:
public AuthenticationResult getAccessToken(AuthorizationCode authorizationCode, String currentUri) throws Throwable {
String authCode = authorizationCode.getValue();
ClientCredential credential = new ClientCredential(clientId, clientSecret);
AuthenticationContext context = null;
AuthenticationResult result = null;
ExecutorService service = null;
try {
service = Executors.newFixedThreadPool(1);
context = new AuthenticationContext(authority + tenant + "/", true, service);
//here are the error
Future<AuthenticationResult> future = context.acquireTokenByAuthorizationCode(authCode, new URI(currentUri), credential, resource, null);
result = future.get();
} catch (ExecutionException e) {
throw e.getCause();
} finally {
service.shutdown();
}
please help me! I send this post to sever for authorization via email, but server answered
"error":"Wrong input parameters"
I know to items is true !and proplem is not in items!
public String RegistrationByEmail(String email, String username, String password) throws IOException {
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy
= new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://speechyard.com/api/register");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
nameValuePairs.add(new BasicNameValuePair("email", email));
nameValuePairs.add(new BasicNameValuePair("username", username));
nameValuePairs.add(new BasicNameValuePair("pssword", password));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
Id_Token_from_website2 = responseHandler(response);
Log.v(TAG, "Id_Token_from_website : " + Id_Token_from_website2);
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
return Id_Token_from_website2;
}
you may have a typo here:
nameValuePairs.add(new BasicNameValuePair("pssword", password));
I think it should be:
nameValuePairs.add(new BasicNameValuePair("password", password));
you forgot the a in password
I have been following this post on how to create an entry point into my spring mvc 3.1 web application for someone to login using a json request.
Spring Security and JSON Authentication
I've got a question about the code below. Inside attemptAuthentication I am adding extra request parameters which are json specific. And then I try to access those parameters in obtainUsername and obtainPassword but the parameters are not there.
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
throws AuthenticationException {
if ("application/json".equals(request.getHeader("Content-Type"))) {
StringBuffer sb = new StringBuffer();
String line = null;
BufferedReader reader;
try {
reader = request.getReader();
while ((line = reader.readLine()) != null){
sb.append(line);
}
//json transformation
ObjectMapper mapper = new ObjectMapper();
JsonLoginRequest loginRequest = mapper.readValue(sb.toString(), JsonLoginRequest.class);
String jsonUsername = loginRequest.getJ_username();
request.setAttribute("jsonUsername", jsonUsername);
String jsonPassword = loginRequest.getJ_password();
request.setAttribute("jsonPassword", jsonPassword);
String jsonStore = loginRequest.getJ_store();
request.setAttribute("jsonStore", jsonStore);
}
catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
String usernameParameter = obtainUsername(request);
String password = obtainPassword(request);
When I do this jsonUsername and jsonStore don't exist even though I added them above.
#Override
protected String obtainUsername(HttpServletRequest request) {
String combinedUsername = null;
if ("application/json".equals(request.getHeader("Content-Type"))) {
String jsonUsername = request.getParameter("jsonUsername");
String jsonStore = request.getParameter("jsonStore");
combinedUsername =
jsonUsername +
SecurityConstants.TWO_FACTOR_AUTHENTICTION_DELIM +
jsonStore;
}else {
String username = super.obtainUsername(request);
String store = request.getParameter(SecurityConstants.STORE_PARAM);
String hiddenStore = request.getParameter(SecurityConstants.HIDDEN_STORE_PARAM);
combinedUsername =
username +
SecurityConstants.TWO_FACTOR_AUTHENTICTION_DELIM +
store +
SecurityConstants.TWO_FACTOR_AUTHENTICTION_DELIM +
hiddenStore;
}
return combinedUsername;
}
Can someone help me with what is wrong? thanks