I was trying to pass ID/PW with post method for jwt token.
I've checked token is returning when debugging, but it's not showing on postman as a header.
String key = "secretKey-test-authorization-jwt-manage-token";
String token = Jwts.builder()
.setSubject(authResult.getName())
.claim("authorities", authResult.getAuthorities())
.setIssuedAt(new Date())
.setExpiration(java.sql.Date.valueOf(LocalDate.now().plusDays(1)))
.signWith(Keys.hmacShaKeyFor(key.getBytes()))
.compact();
response.addHeader("Authorization", "Bearer " + token);
Related
Hello team I have a Application on https://console.cloud.google.com of type Desktop
once after signin with the test user credentials , i have returned successfully and then trying to get the token using the
final String tokenUrl = "https://oauth2.googleapis.com/token";
// The original redirect URL
final URI redirectUri = new URI(this.redirectUri);
// Using HttpClient to make the POST to exchange the auth code for the token
HttpClient client = HttpClientBuilder.create().build();
HttpPost post = new HttpPost(tokenUrl);
// Adding the POST params to the request
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
urlParameters.add(new BasicNameValuePair("code", code));
urlParameters.add(new BasicNameValuePair("client_id", googleClientId));
urlParameters.add(new BasicNameValuePair("client_secret", googleClientsecret));
urlParameters.add(new BasicNameValuePair("redirect_uri", redirectUri.toString()));
urlParameters.add(new BasicNameValuePair("scope", scope));
urlParameters.add(new BasicNameValuePair("grant_type", grantType));
post.setEntity(new UrlEncodedFormEntity(urlParameters));
// Execute the request
System.out.println(post.toString());
HttpResponse response = client.execute(post);
// Print the status code
System.out.println("Response Code : " + response.getStatusLine().getStatusCode());
// Get the content as a String
String content = EntityUtils.toString(response.getEntity());
System.out.println("Result : " + content.toString());
am getting the error as below
Response Code : 400
Result : {
"error": "invalid_request",
"error_description": "client_secret is missing."
}
i know am not using google API's to get the token , but the api here am using also should work right?
please please help me here
i am trying to get a access token and refresh token to access google sheets data but every time i try to get a token i get the same error "invalid grant type" i am using grant type authorization code. i am trying to get a access token using postman and it worked but its not working in my pycharm.
import http.client
conn = http.client.HTTPSConnection("oauth2.googleapis.com")
payload = 'code=<your code here>A&client_id=<your client id>&client_secret=<your client secret>redirect_uri=http%3A%2F%2F127.0.0.1%3A8000%2F&grant_type=authorization_code'
headers = {
'Content-Type': 'application/x-www-form-urlencoded'
}
conn.request("POST", "/token", payload, headers)
res = conn.getresponse()
data = res.read()
print(data.decode("utf-8"))
i tried this and i tried to get token through request also
import requests
url = "https://oauth2.googleapis.com/token"
payload='code=<your-code-here>%0A&client_id=<your client id>&client_secret=<your client secret>&redirect_uri=http%3A%2F%2F127.0.0.1%3A8000%2Fgsheet&grant_type=authorization_code'
headers = {
'Authorization': 'Bearer ya29.a0AfH6SMC0nVvV0m77pPvgNLnWXopI7VKvoBdVSDSgvi6Fx0mrPYQf9xU6j3UJCA3vrWRi62Tqfv0PFZd9uo59C2NQzraV1MBtAAF1G_tTRXIXELxsbmjf5weGJ6FkmJknDof2riZCnpYzK-J2EWmWKQVeetwd',
'Content-Type': 'application/x-www-form-urlencoded'
}
response = requests.request("POST", url, headers=headers, data=payload)
print(response.text)
The method (.request) definition is like this:
HTTPConnection.request(method, url, body=None, headers={}, *, encode_chunked=False)
And your arguments doesn't match!
Reference: https://docs.python.org/3/library/http.client.html#http.client.HTTPConnection.request
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.
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.
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);