Spring Security and Angular 5 - spring-security

Right now I'm sending username and password through header from my angular 5 app after successful login to access spring rest api. After Successful I'm getting unique sessionId from spring in response can I use that ID instead of credentials to authenticate
angular code
let d=localStorage.getItem('currentUser');
let headers = new Headers();
var user=JSON.parse(d);
headers.append('Accept', 'application/json');
// creating base64 encoded String from user name and password
var base64Credential: string = btoa(user.principal.username+ ':' + user.principal.password);
headers.append("Authorization", "Basic " + base64Credential);
let options = new RequestOptions({ headers: headers
});
var self = this;
self.greeting = {id:'', content:''};
http.get(this.url,options).map(response => self.greeting = response.json);

You can use jwt token for this.
Store the sessionId in localStorage or a cookie.
Send it inside the request header in each and every request (use httpInteceptor for this)
https://medium.com/#ryanchenkie_40935/angular-authentication-using-the-http-client-and-http-interceptors-2f9d1540eb8
In the Java application, add filter to all the requests, which need to be protected.

Related

How to implement OAuth2.0 using client credentials grant-type in a way that it supports Json raw body with token request in c#

My project is a web api project which is using owin for generating token after authentication. it is built using asp.net framework.
It currently accepts token request in below format -
var client = new RestClient("http://localhost:63202/1.0/token");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddParameter("grant_type", "client_credentials");
request.AddParameter("client_id", "12345667");
request.AddParameter("client_secret", "secret");
I want my API to support Json raw body instead of URL encoded one with the token request as below -
var client = new RestClient("http://localhost:63202/1.0/token");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/json");
var body = #"{" + "\n" +
#" "grant_type": "client_credentials"," + "\n" +#" "client_id": "1234567890""," + "\n" +#"client_secret": "channelsintegration123456789012345" + "\n" +
#"}"
request.AddParameter("application/json", body, ParameterType.RequestBody);
Issue - When the request is made and ValidateClientAuthentication() method is hit, the context doesn't have client id and client secret when I make the above (#2) request.

Search for Twitter handles using Google Apps Script and Twitter API - doesn't work

I'm trying to find Twitter handles from a spreadsheet containing names of people.
I can't get it work with this request, which I believe is the one I should be using as I only have peoples names (e.g. Adam Smith): api.twitter.com/1.1/users/search.json?q=
I get the following error:
Request failed for api.twitter.com/1.1/users/search.json?q=Name returned code 403. Truncated server response: {"errors":[{"message":"Your credentials do not allow access to this resource","code":220}]} (use muteHttpExceptions option to examine full response) (line 38).'
I've tried searching this error but that hasn't helped me so far.
If I use, for example, this request, it works: api.twitter.com/1.1/users/show.json?screen_name=
So I can get the screen_name back in the spreadsheet, but that's pointless obviously because it needs the screen name to work in the first place...
The whole thing is based on this work, all the requests in that code work for me. It's just this search request that doesn't work. What's going wrong?
var CONSUMER_KEY = 'x';
var CONSUMER_SECRET = 'x';
function getTwitterHandles(name) {
// Encode consumer key and secret
var tokenUrl = "https://api.twitter.com/oauth2/token";
var tokenCredential = Utilities.base64EncodeWebSafe(
CONSUMER_KEY + ":" + CONSUMER_SECRET);
// Obtain a bearer token with HTTP POST request
var tokenOptions = {
headers : {
Authorization: "Basic " + tokenCredential,
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"
},
method: "post",
payload: "grant_type=client_credentials"
};
var responseToken = UrlFetchApp.fetch(tokenUrl, tokenOptions);
var parsedToken = JSON.parse(responseToken);
var token = parsedToken.access_token;
// Authenticate Twitter API requests with the bearer token
var apiUrl = 'https://api.twitter.com/1.1/users/search.json?q=screen_name='+name;
var apiOptions = {
headers : {
Authorization: 'Bearer ' + token
},
"method" : "get"
};
var responseApi = UrlFetchApp.fetch(apiUrl, apiOptions);
var result = "";
if (responseApi.getResponseCode() == 200) {
// Parse the JSON encoded Twitter API response
var tweets = JSON.parse(responseApi.getContentText());
return tweets.id
}
Logger.log(result);
}
Edit: deleted the https a few times because of the URL limit
You can not search for users using application-only authentication (bearer token). See https://dev.twitter.com/oauth/application-only. A user context (access token) is needed for that request. You can get your own access token from https://apps.twitter.com.

IdentityServer3 Response status code does not indicate success: 400 (Bad Request)

I always get Bad Request 400 from IdentityServer3. I am trying for 3 days now but no luck :( Anyone could please tell me what am I doing wrong?
I am trying to access IdentityServer3 hosted by another vendor that I have no control. The vendor has asked us to implement Implement OAuth2 authentication with Bearer token. The vendor provided us with the Client ID, Client Secret and the URL to be used is http://www.xxxxxx.com/identity/connect/token
The vendor told us to use to request bearer token and use it in the request headers Authorization: Bearer
I can successfully obtain the bearer token from vendor. But when I call the
GET /api/profiles/myemailaddress#gmail.com I get Bad Request 400
Here is what I have done:
TokenClient client = new TokenClient("http://www.xxxxxx.com/identity/connect/token", "myclientid", "myclientsecret", AuthenticationStyle.PostValues);
var response = await client.RequestResourceOwnerPasswordAsync("myemailaddress#gmail.com", "mypassword", "profile"); // successfully gives me the token
i got the access token, now i want to use the token to request user profile:
var clienthttp = new HttpClient();
clienthttp.BaseAddress = new Uri("http://www.xxxxxx.com");
clienthttp.SetBearerToken(response.AccessToken);
var json = await clienthttp.GetStringAsync("http://www.xxxxxx.com/api/profiles/myemailaddress#gmail.com"); // error Bad Request 400
Additional Info:
"scopes_supported":["profile","offline_access"],
"claims_supported":[]
Thank you.
The vendor was expecting additional value in the header. Since my request was missing that additional value, they returned Bad Request. I had to modify my code to find the exact reason of bad request.
Here is the updated code, might be useful for someone:
var client = new HttpClient();
client.BaseAddress = new Uri("http://www.xxxxx.com");
client.SetBearerToken(response.AccessToken);
var callApiResponse = client.GetAsync("api/profiles/myemailaddress#gmail.com").Result;
string tokenresponse = callApiResponse.StatusCode.ToString();
string clientresult = callApiResponse.Content.ReadAsStringAsync().Result;
tokenresponse: "Bad Request 400"
clientresult: "Missing CompanyID in the header"
Then I knew that they also expect companyid in the header so I added it. then all was good.
client.DefaultRequestHeaders.Add("CompID", "xxxxxx");
I had a similar error (Response status code does not indicate success: 400 (Bad Request)) for different resource not identity server. i manage to resolve that using FormUrlEncodedContent
Refer below code
using (HttpClient client = new HttpClient())
{
string baseUrl = "https://*******.com/****"
Dictionary<string, string> jsonValues = new Dictionary<string, string>();
jsonValues.Add("username", "******");
jsonValues.Add("password", "******");
var contenta = new FormUrlEncodedContent(jsonValues);
var response = await client.PostAsync(baseUrl, contenta);
using (HttpContent content = response.Content)
{
string data = await content.ReadAsStringAsync();
if (data != null)
{
Console.WriteLine(data);
}
}
}

Scribe + Xing => Invalid OAuth signature

I'm trying to use scribe with XING and I'm always getting following answer:
Can't extract token and secret from this: '{"message":"Invalid OAuth signature","error_name":"INVALID_OAUTH_SIGNATURE"}'
I have a working login process, get back an oauth_token and an oauth_verifier and tried to to change the defaultly selected HMACSha1 Singature with a PlainText signature, but I'll always get the above mentioned result...
Any ideas on why this happens?
Using the default DefaultApi10a and XingApi from scribe always fails at the above mentioned step...
EDIT - Code
// Creating the service
// callback is needed to stop redirecting in the webview
OAuthService service = new ServiceBuilder()
.provider(XingApi.class)
.apiKey(apiKey)
.apiSecret(apiSecret)
.callback("http://www.xing.com")
.build();
Step 1: get request token + auth url
RequestToken requestToken = service.getRequestToken();
String authUrl = service.getAuthorizationUrl(requestToken );
Step 2: load the auth url in a webview + check the redirect url and cancel redirection based on callback
for example, redirection url look like following: http://www.xing.com?oauth_token=a2191ab84c9e0f85cf0c&oauth_verifier=4978
Step 3: extract oauth_token + oauth_verifier from returned url
String oauthToken = ...; // a2191ab84c9e0f85cf0c in the example
String oauthVerifier = ...; // 4978 in the example
Step 4: get access token => this fails
Token requestToken = new Token(oauthToken, oauthVerifier); // reusing the request token from above results in invalid request token answer from xing!
Verifier v = new Verifier(oauthVerifier);
Token accessToken = service.getAccessToken(requestToken, v);
Remove:
Token requestToken = new Token(oauthToken, oauthVerifier); // reusing the request token from above results in invalid request token answer from xing!
line from step 4.
You have to keep request token to retrieve access token using it and verifier (4 digits PIN) from Xing.
EDIT - code added:
OAuth10aService service = new ServiceBuilder()
.apiKey("44a4f9c1a9daa88f4da2")
.apiSecret("2fc8ca373dab772acc4de7ce22718f8fced6919c")
.callback("https://redirect.example.com")
.build(XingApi.instance());
final Token requestToken = service.getRequestToken();
System.out.println(service.getAuthorizationUrl(requestToken));
System.out.println("Paste the verifier here");
System.out.print(">>");
Scanner in = new Scanner(System.in);
Verifier verifier = new Verifier(in.nextLine());
System.out.println();
in.close();
// Trade the Request Token and Verfier for the Access Token
Token accessToken = service.getAccessToken(requestToken, verifier);
System.out.println("Got the Access Token! " + accessToken);

Forms Authentication Cookie Missing in HttpWebResponse

I am sending a post request from an ASP.NET MVC 2.0 Controller to another site on the same domain using HttpWebRequest. I am sending username and password to logon to the site. That site uses forms authentication. So it sets authentication cookie. But when I get response in HttpWebResponse object, I find cookie neither in cookie container nor inside header (no Cookie or Set-Cookie header found). Let me add some code snippet here used in the MVC controller:
HttpWebRequest httpRequest = (HttpWebRequest) WebRequest.Create(url);
httpRequest.Method = "POST";
httpRequest.ContentType = "application/x-www-form-urlencoded";
httpRequest.ContentLength = postData.Length;
if (httpRequest.CookieContainer == null)
{
//httpRequest.CookieContainer = new CookieContainer();
}
httpRequest.Headers.Add(HttpRequestHeader.Cookie, "a=b");
var streamWriter = new StreamWriter(httpRequest.GetRequestStream());
streamWriter.Write(postData);
streamWriter.Close();
HttpWebResponse httpResponse = (HttpWebResponse) httpRequest.GetResponse();
string postBody = "";
using (StreamReader reader = new StreamReader(httpResponse.GetResponseStream()))
{
postBody = reader.ReadToEnd();
}
return this.Content(postBody);
Please note that I am not using cookie container and cookie header at the same time in HttpWebRequest.
I don't understand what I am missing here to get authentication cookie in web response.
Try to use
request.CookieContainer.Add(new Cookie("a", "b"));
instead of adding cookie as a header.

Resources