I'm implementing the SSO process (OAuth 2.0) using DotNetOpenAuth example. The solution has 3 projects (Client Web, Authorization Server, and Resource Server) I got an issue in the step of processing user authorization response after Authorization Server returned the Authorization Code to client.
http://localhost/OAuthClient/SampleWcf2.aspx?code=xxx&state=L6SAxlXhlxwsBRcTCK3IAw
Exception is:
[WebException: The remote server returned an error: (400) Bad Request.]
System.Net.HttpWebRequest.GetResponse() +8765848
DotNetOpenAuth.Messaging.StandardWebRequestHandler.GetResponse(HttpWebRequest request, DirectWebRequestOptions options) +271
[ProtocolException: Error occurred while sending a direct message or getting the response.]
DotNetOpenAuth.Messaging.StandardWebRequestHandler.GetResponse(HttpWebRequest request, DirectWebRequestOptions options) +2261
DotNetOpenAuth.Messaging.Channel.RequestCore(IDirectedProtocolMessage request) +516
DotNetOpenAuth.Messaging.Channel.Request(IDirectedProtocolMessage requestMessage) +138
DotNetOpenAuth.OAuth2.ClientBase.UpdateAuthorizationWithResponse(IAuthorizationState authorizationState, EndUserAuthorizationSuccessAuthCodeResponse authorizationSuccess) +210
DotNetOpenAuth.OAuth2.WebServerClient.ProcessUserAuthorization(HttpRequestBase request) +904
OAuthClient.SampleWcf2.Page_Load(Object sender, EventArgs e) +118
System.Web.UI.Control.LoadRecursive() +71
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3178
Here's my code:
protected void Page_Load(object sender, EventArgs e) {
if (!IsPostBack) {
// Check to see if we're receiving a end user authorization response.
var authorization = Client.ProcessUserAuthorization();
//Temp
if (authorization != null)
{
// We are receiving an authorization response. Store it and associate it with this user.
Authorization = authorization;
Response.Redirect(Request.Path); // get rid of the /?code= parameter
}
}
if (Authorization != null) {
// Indicate to the user that we have already obtained authorization on some of these.
foreach (var li in this.scopeList.Items.OfType<ListItem>().Where(li => Authorization.Scope.Contains(li.Value))) {
li.Selected = true;
}
this.authorizationLabel.Text = "Authorization received!";
if (Authorization.AccessTokenExpirationUtc.HasValue) {
TimeSpan timeLeft = Authorization.AccessTokenExpirationUtc.Value - DateTime.UtcNow;
this.authorizationLabel.Text += string.Format(CultureInfo.CurrentCulture, " (access token expires in {0} minutes)", Math.Round(timeLeft.TotalMinutes, 1));
}
}
this.getNameButton.Enabled = this.getAgeButton.Enabled = this.getFavoriteSites.Enabled = Authorization != null;
}
Related
I have developed a small UI5 application with OData calls and I am implementing the authorizations. On the server I have a spring web security application where have I have restricted the MemebersList.view.xml to users that are logged in. My idea is to create under the folders view and controller a folder user for the logged in users with the files that are restricted.
After the user is successfully logged in I receive the token to make further OData calls.
Question 1:
Can I restrict in UI5 the resources(XML views and JS controllers) so that the user only has direct access when is logged in or the sources have to be visible allways? For example I want to avoid that the user can directly enter
http://localhost:9004/webapp/view/user/MembersList.view.xml or
http://localhost:9004/webapp/controller/user/MembersList.controllers.js and see the code
Question 2:
Can I somehow send the Token in the header when I call the view MembersList with the getRouter().navTo('MembersList')? I guess in this case I would also need somehow to pass the token to the call for the MembersList.controllers.js. Maybe set that all the http calls include the token?
Maybe there is a better approach
WebSecurityConfig.java
#Override
protected void configure(HttpSecurity http) throws Exception {
http.cors()
.and()
.csrf().disable()
.exceptionHandling().authenticationEntryPoint(jwtEntryPoint)
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/**/user/**").hasRole("USER")
.antMatchers("/**/admin/**").hasRole("ADMIN")
.antMatchers("/",
"/favicon.ico",
"/**/*.json",
"/**/*.xml",
"/**/*.properties",
"/**/*.woff2",
"/**/*.woff",
"/**/*.ttf",
"/**/*.ttc",
"/**/*.ico",
"/**/*.bmp",
"/**/*.png",
"/**/*.gif",
"/**/*.svg",
"/**/*.jpg",
"/**/*.jpeg",
"/**/*.html",
"/**/*.css",
"/**/*.js",
"/**/*.html").permitAll()
.antMatchers("/**/api/auth/**").permitAll()
.anyRequest().authenticated();
http.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
}
onClickEvent:
onLoginTap : function() {
var navigator_info = window.navigator;
var screen_info = window.screen;
var uid = navigator_info.mimeTypes.length;
uid += navigator_info.userAgent.replace(/\D+/g, '');
uid += navigator_info.plugins.length;
uid += screen_info.height || '';
uid += screen_info.width || '';
uid += screen_info.pixelDepth || '';
this.loginBody.getData().email = this.login.getData().user;
this.loginBody.getData().password = this.login.getData().password;
this.loginBody.getData().deviceId = uid;
// create XHR object
var xhttp = new XMLHttpRequest();
var that = this;
// gets everytime fired when the XHR request state changes
xhttp.onreadystatechange = function() {
// 4 means request is finished and response is ready
// 200 means request is just fine
if (this.readyState == 4 && this.status == 200) {
// "this" refers here to the XHR object
var json = JSON.parse(this.responseText)
if (json.accessToken !== null) {
that.login.getData().accessToken = json.accessToken;
that.getRouter().navTo("MembersList");
}
}
};
// set the XHR request parameters
xhttp.open("POST", "http://localhost:9004/api/auth/login", true);
xhttp.setRequestHeader("Content-Type", "application/json");
// fire the XHR request
xhttp.send(JSON.stringify(this.loginBody.getData()));
}
I have an MVC Web API project that I am working on. I created a controller with an action. I am able to hit the action properly using Postman, but when an external system tries to reach my controller, it gets a 500 error. The owner of the external service cannot give me any details beyond that, they can only retry the request.
Here is one of the log entries of their requests in IIS log
#Fields: date time s-ip cs-method cs-uri-stem cs-uri-query s-port cs-username c-ip cs(User-Agent) cs(Referer) sc-status sc-substatus sc-win32-status time-taken
2017-02-15 20:38:58 192.168.2.34 POST /Route/to/actionName 8002 - 192.168.2.37 Apache-HttpClient/4.5.2+(Java/1.8.0_102) - 500 0 0 146
First I thought may be the action is being hit, so I added an exception handler and added logging.
[Route("actionName")]
[HttpPost]
public IHttpActionResult actionName(MessageModel message)
{
try
{
// code to handle the action
}
catch (Exception e)
{
// Code to log exception in the log file
}
}
Tried above and saw nothing in the log, I have run tests for failed requests to make sure the above exception handler logs and it does.
So the next thing I decided to do was to handle application level errors in Global.asax and log exception there.
protected void Application_Error(object sender, EventArgs e)
{
if (Request.HttpMethod == "POST")
{
var request = SomeMethodToReadRequestContentsInString();
var service = new SomeExceptionLoggingService();
var exception = Server.GetLastError();
if (exception == null)
{
exception = new ApplicationException("Unknown error occurred");
}
service.LogException(exception, Request.UserHostAddress, Request.UserAgent, request);
}
}
And to my surprise, nothing in the log file.
So then I decided to log ALL Post requests and see if I register ANYTHING in the log.
protected void Application_EndRequest(object sender, EventArgs e)
{
if (Request.HttpMethod == "POST")
{
var request = Helper.ReadStreamUnknownEncoding(Request.InputStream);
var service = new InterfaceTestingService();
var exception = Server.GetLastError();
if (exception == null)
{
exception = new ApplicationException("No Error in this request");
}
service.LogException(exception, Request.UserHostAddress, Request.UserAgent, request);
}
}
And again, nothing!
How do I catch this bug? My goal is to see the Content-Type, and contents.
I tried to add a Custom Field in IIS log settings to include `Content-Type', but the log files still don't have that.
I added a handler for Application_BeginRequest logging everything I did in Application_EndRequest. And it turns out, the content-length was zero, and there was no content. I also restarted IIS Web Server to get it to log custom fields too.
What's strange is that if I send empty content through Postman, I get the action code executed but for some reason when they do it, it doesn't.
We are trying to use Exact Online API. It is using Apache OAuth 2.0 framework. For that we followed the below document.
https://developers.exactonline.com/#OAuth_Tutorial.html%3FTocPath%3DAuthentication%7C_____2
I successfully able to get the authorization code but failing to get the access_token with exception like below.
OAuthProblemException{error='invalid_request', description='Missing parameters: access_token', uri='null', state='null', scope='null', redirectUri='null', responseStatus=0, parameters={}}
My code is like this.
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
try {
OAuthAuthzResponse oar = OAuthAuthzResponse.oauthCodeAuthzResponse(request);
String code = oar.getCode();
OAuthClientRequest oAuthrequest = OAuthClientRequest
.tokenLocation("https://start.exactonline.co.uk/api/oauth2/token")
.setGrantType(GrantType.AUTHORIZATION_CODE)
.setClientId("my client id")
.setClientSecret("my client secret")
.setRedirectURI("http://localhost:8080/SampleServlet/AuthServlet")
.setCode(code)
.buildBodyMessage();
OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());
GitHubTokenResponse oAuthResponse = oAuthClient.accessToken(oAuthrequest, "POST",GitHubTokenResponse.class);
out.println("Access Token = " + oAuthResponse.getAccessToken());
} catch (OAuthSystemException ex) {
Logger.getLogger(AuthServlet.class.getName()).log(Level.SEVERE, null, ex);
} catch (OAuthProblemException ex) {
Logger.getLogger(AuthServlet.class.getName()).log(Level.SEVERE, null, ex);
} finally {
out.close();
}
}
Can some one please help me to sort this out.
Finally i resolved this issue with a simple change. The problem is with the line
GitHubTokenResponse oAuthResponse = oAuthClient.accessToken(oAuthrequest, "POST",GitHubTokenResponse.class);
Instead of this we have to use either of the below lines to get the access token properly.
OAuthJSONAccessTokenResponse oAuthResponse = oAuthClient.accessToken(oAuthrequest, OAuth.HttpMethod.POST);
(Or)
OAuthAccessTokenResponse oAuthResponse =oAuthClient.accessToken(oAuthrequest,OAuth.HttpMethod.POST);
I started playing with tweetinvi to connect to twitter api. I keep getting "The remote server returned an error: (401) Unauthorized." error message when I call CredentialsCreator.GetCredentialsFromVerifierCode() after being redirected.
I added my phone to my account.
I made use the Consumer Key and Consumer Secret are the same.
I made use that my time is current
The callback url in app settings is http://127.zero.zero.1:53260/
I'm kinda of lost on what to do next.
This is the only code that I use:
protected void Page_Load( object sender, EventArgs e )
{
Tweetinvi.WebLogic.TemporaryCredentials applicationCredentials = (Tweetinvi.WebLogic.TemporaryCredentials)CredentialsCreator.GenerateApplicationCredentials( Properties.Settings.Default.TwitterConsumerKey, Properties.Settings.Default.TwitterConsumerSecret );
if (Request["oauth_token"] == null)
{
string url = CredentialsCreator.GetAuthorizationURLForCallback( applicationCredentials, "http://127.0.0.1:53260/twitter.aspx" );
Response.Redirect( url, false );
}
else
{
string verifierCode = Request["oauth_verifier"];
// error calling this code
var newCredentials = CredentialsCreator.GetCredentialsFromVerifierCode( verifierCode, applicationCredentials );
Console.WriteLine( "Access Token = {0}", newCredentials.AccessToken );
Console.WriteLine( "Access Token Secret = {0}", newCredentials.AccessTokenSecret );
}
}
Looks like you have everything correct. It might be the library you are using. Have you tried LinqToTwitter?
They have several examples you can test at http://linqtotwitter.codeplex.com/SourceControl/latest#ReadMe.txt. Just download their source files and you'll find Linq2TwitterDemos_WebForms project that you can text out.
I am trying to authenticate with Google using OAuth 2.0 for GAMv2 Apps.
GoogleCredential.Builder credentialBuilder = new GoogleCredential.Builder();
credentialBuilder.setTransport(httpTransport).setJsonFactory(jsonFactory);
credentialBuilder.setServiceAccountId(serviceAccountId);
credentialBuilder.setServiceAccountPrivateKeyFromP12File(new File(p12FileURL.toURI()));
credentialBuilder.setServiceAccountScopes(scopes);
credentialBuilder.setServiceAccountUser(userEmail);
credential = credentialBuilder.build();
credential.refreshToken();
Oauth2 userInfoService = new Oauth2.Builder(new NetHttpTransport(), new JacksonFactory(), credential).setApplicationName(applicationName).build();
Userinfoplus userInfo = null;
try
{
userInfo = userInfoService.userinfo().get().execute();
}
catch (IOException e)
{
logger.error("Exception_Thrown while getting User Info:", e);
}
I am using the above code for getting the userInfo and facing the following exception :
java.net.SocketTimeoutException: Read timed out
at java.net.SocketInputStream.socketRead0(Native Method)
at java.net.SocketInputStream.read(SocketInputStream.java:129)
at com.sun.net.ssl.internal.ssl.InputRecord.readFully(InputRecord.java:293)
at com.sun.net.ssl.internal.ssl.InputRecord.read(InputRecord.java:331)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:798)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readDataRecord(SSLSocketImpl.java:755)
at com.sun.net.ssl.internal.ssl.AppInputStream.read(AppInputStream.java:75)
at java.io.BufferedInputStream.fill(BufferedInputStream.java:218)
at java.io.BufferedInputStream.read1(BufferedInputStream.java:258)
at java.io.BufferedInputStream.read(BufferedInputStream.java:317)
at sun.net.www.http.HttpClient.parseHTTPHeader(HttpClient.java:687)
at sun.net.www.http.HttpClient.parseHTTP(HttpClient.java:632)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1195)
at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:379)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(HttpsURLConnectionImpl.java:318)
at com.google.api.client.http.javanet.NetHttpResponse.<init>(NetHttpResponse.java:36)
at com.google.api.client.http.javanet.NetHttpRequest.execute(NetHttpRequest.java:94)
at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:965)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:410)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:343)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:460)
Until last few days, it was fine. Only in a couple of days now we are facing this issue.
Can anyone help with this issue ?
Thanks in advance.
you can get instance of HttpRequestInitializer from Oauth2.Builder and pass it as input parameter
private static HttpRequestInitializer setHttpTimeout(final HttpRequestInitializer requestInitializer) {
return new HttpRequestInitializer() {
#Override
public void initialize(HttpRequest httpRequest) throws IOException {
requestInitializer.initialize(httpRequest);
httpRequest.setConnectTimeout(3 * 60000); // 3 minutes connect timeout
httpRequest.setReadTimeout(3 * 60000); // 3 minutes read timeout
}
};
}