I'm really new to using retrofit2. I'm trying to send access token to the backend from mobile app and authenticate the user via Google but I can not do it properly. The backend returns 400.
My code is like this.
views.py
from allauth.socialaccount.providers.google.views import GoogleOAuth2Adapter
from rest_auth.registration.views import SocialLoginView
class GoogleLogin(SocialLoginView):
adapter_class = GoogleOAuth2Adapter
urls.py
path('rest-auth/google/', GoogleLogin.as_view()),
And my Java code (I'm using retrofit2)
public interface ApiService {
// login
#POST("/rest-auth/google/")
Call<String> login(#Header("access_token") String accessToken);
MainActivity.java
private void login() {
ApiService service = ApiClient.getService();
service.login(mAuthToken).enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, Response<String> response) {
if (!response.isSuccessful()) {
Toast.makeText(MainActivity.this, "Code:" + response.code(), Toast.LENGTH_LONG).show();
return;
}
Toast.makeText(MainActivity.this, "Success!", Toast.LENGTH_LONG).show();
}
#Override
public void onFailure(Call<String> call, Throwable t) {
mTextViewResult.setText(t.getMessage());
}
});
}
mAuthToken is access token. I think I'm wrong with the way to pass the access token to backend. I might be wrong with retrofit2 part. What am I wrong with this?
Update
I found a thing. The access token I get in Android and the access token I get when I login via website is apparently different. I deleted the user and input the access token in the html form manually, the request is accepted.
So I guess there is a problem with access token I get in Android but I have no idea how I can fix this.
Related
I want to authenticate AAD users to access powerBi resources through MSAL by using application ID and secret. So i want to get the access token and cache it in SQL Db.
went through the documentation but it explains the scenario of using MSAL for sign-in.
also went through the tutorial
i was able to to do the necessary implementations to get the token.
how can i get the access token and cache it, in a scenario like this?
As indicated in other answers, caching tokens are useful in case when you have users signing in, as once the access token expires (typically after 1 hour), you don't want to keep prompting the users to re-authenticate.
So help with these scenarios, Azure AD issues a refresh token along with an access token that is used to fetch access tokens once they expire. Caching is required to cache these refresh tokens as they are valid for 90 days.
When an app signs as itself (and not signing in a user), the client credentials flow is used and it only needs the app id (clientId) and the credential (secret/certificate) to issue an access token. The MSAL library will automatically detect when the access token expires and will use the clientId/credential combination to automatically get a new access token. So caching is not necessary.
The sample you should be looking at is this one.
I'n not sure to understand, I hope these few lines of code will help you.
First, customize token cache serialization :
public class ClientApplicationBuilder
{
public static IConfidentialClientApplication Build()
{
IConfidentialClientApplication clientApplication =
ConfidentialClientApplicationBuilder
.Create(ClientId)
.WithRedirectUri(RedirectUri)
.WithClientSecret(ClientSecret)
.Build();
clientApplication.UserTokenCache.SetBeforeAccessAsync(BeforeAccessNotification);
clientApplication.UserTokenCache.SetAfterAccessAsync(AfterAccessNotification);
return clientApplication;
}
private static async Task<byte[]> GetMsalV3StateAsync()
{
//TODO: Implement code to retrieve MsalV3 state from DB
}
private static async Task StoreMsalV3StateAsync(byte[] msalV3State)
{
//TODO: Implement code to persist MsalV3 state to DB
}
private static async Task BeforeAccessNotification(TokenCacheNotificationArgs args)
{
byte[] msalV3State = await GetMsalV3StateAsync();
args.TokenCache.DeserializeMsalV3(msalV3State);
}
private static async Task AfterAccessNotification(TokenCacheNotificationArgs args)
{
if (args.HasStateChanged)
{
byte[] msalV3State = args.TokenCache.SerializeMsalV3();
await StoreMsalV3StateAsync(msalV3State);
}
}
}
Here's an example to acquire token (by Authorization Code) :
public class MsAccountController
: Controller
{
private readonly IConfidentialClientApplication _clientApplication;
public MsAccountController()
{
_clientApplication = ClientApplicationBuilder.Build();
}
[HttpGet]
public async Task<IActionResult> Index()
{
Uri authorizationRequestUrl = await _clientApplication.GetAuthorizationRequestUrl(ClientApplicationHelper.Scopes).ExecuteAsync();
string authorizationRequestUrlStr = authorizationRequestUrl.ToString();
return Redirect(authorizationRequestUrlStr);
}
[HttpGet]
public async Task<IActionResult> OAuth2Callback(string code, string state)
{
AuthenticationResult authenticationResult = await _clientApplication.AcquireTokenByAuthorizationCode(scopes, code).ExecuteAsync();
return Ok(authenticationResult);
}
}
Finally, acquire a token silently and use auth result for your API client :
public class TaskController
: Controller
{
private readonly IConfidentialClientApplication _clientApplication;
public TaskController()
{
_clientApplication = ClientApplicationBuilder.Build();
}
[HttpGet]
public async Task<IActionResult> Index()
{
IEnumerable<IAccount> accounts = await _clientApplication.GetAccountsAsync();
AuthenticationResult result = await _clientApplication.AcquireTokenSilent(ClientApplicationHelper.Scopes, accounts.FirstOrDefault()).ExecuteAsync();
//TODO: Create your API client using authentication result
}
}
Regards
You can cache the access token (actually, the library does this already), but it is valid for 1 hour only. So it makes no sense to save it in a database, because it will expire quickly.
You should cache the credentials needed to obtain the token (user name and password, app ID and secret, or certificate) and obtain a token when needed.
I've done this for a confidential client application, where I connected to O365 in order to send email.
First, register your app in azure app as the docs say.
Then, set up your confidential client application and use as singleton.
var app = ConfidentialClientApplicationBuilder.Create(clientId)
.WithClientSecret(clientSecret)
.WithRedirectUri(redirectUri)
.WithLegacyCacheCompatibility(false)
.WithAuthority(AadAuthorityAudience.AzureAdAndPersonalMicrosoftAccount)
.Build();
app.AddDistributedTokenCache(services => {
services.AddDistributedTokenCaches();
services.AddDistributedSqlServerCache(options => {
options.SchemaName = "dbo";
options.TableName = "O365TokenCache";
options.ConnectionString = sqlCacheConnectionString;
options.DefaultSlidingExpiration = TimeSpan.FromMinutes(90);
});
});
services.AddSingleton<IConfidentialClientApplication>(app);
The first time you connect a user, you need to redirect to Microsoft identity. You can create the URL using:
var authUrl = await app.GetAuthorizationRequestUrl(new[] { "email", "offline_access", "https://outlook.office.com/SMTP.Send" }).ExecuteAsync();
(Check your scopes are what you want)
When they come back to your redirect url you then get the code from query string and acquire the refresh token:
var token = await app.AcquireTokenByAuthorizationCode(scopes, code).ExecuteAsync();
When you do this, MSAL will cache the access token and refresh token for you, but here's the thing they don't mention: you have to create the table in SQL yourself! If you don't, it just silently fails.
dotnet tool install -g dotnet-sql-cache
dotnet sql-cache create "<connection string>" dbo O365TokenCache
Once you have the access token the first time you can use the following later
var account = await app.GetAccountAsync(accountId);
var token = await app.AcquireTokenSilent(scopes, account).ExecuteAsync();
When you get the access token the first time, you need to look at token.Account.HomeAccountId.Identifier as this is the ID that you need when you call GetAccountAsync. For some reason, GetAccountsAsync (note the extra "s") always returns empty for me but passing the correct ID to GetAccountAsync does return the right one.
For me, I simply store that ID against the logged in user so that I can get that ID at a later time.
I have to call web service through java. When i hit the web-service URL in browser it asks for user name and password and i can see the result,
But when i am trying to call it using java code i am getting error like
You are not authorized to view this page BODY { font: 8pt/12pt verdana } H1 { font: 13pt/15pt verdana } H2 { font: 8pt/12pt verdana } A:link { color: red } A:visited { color: maroon }You are not authorized to view this pageYou do not have permission to view this directory or page using the credentials that you supplied because your Web browser is sending a WWW-Authenticate header field that the Web server is not configured to accept.Please try the following:Contact the Web site administrator if you believe you should be able to view this directory or page.Click the Refresh button to try again with different credentials.HTTP Error 401.2 - Unauthorized: Access is denied due to server configuration.Internet Information Services (IIS)Technical Information (for support personnel)Go to Microsoft Product Support Services and perform a title search for the words HTTP and 401.Open IIS Help, which is accessible in IIS Manager (inetmgr), and search for topics titled About Security, Authentication, and About Custom Error Messages.
i am not able access the the result using SOAP UI
i am really stuck ,i tried using httpclient/jersey
please help how can i send username and password using java code
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.NTCredentials;
import org.apache.http.auth.params.AuthPNames;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.params.AuthPolicy;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
public class NTLM_TRY2 {
/**
* #param args
*/
public static void main(String[] args) throws Exception{
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpget = new HttpGet("http://10.0.134.114/eBill/bpsWebService.asmx");
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(AuthScope.ANY,
new NTCredentials("abc", "acb#578", "", ""));
java.util.List<String> authtypes = new ArrayList<String>();
authtypes.add(AuthPolicy.NTLM);
authtypes.add(AuthPolicy.DIGEST);
authtypes.add(AuthPolicy.BASIC);
httpclient.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF,
authtypes);
httpclient.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF,
authtypes);
localContext.setAttribute(ClientContext.CREDS_PROVIDER, credsProvider);
HttpResponse response = httpclient.execute(httpget, localContext);
System.out.println("Response code: " + response.getStatusLine());
}
}
If it is basic authentication you have to send the user an password in the header of the request.
See this question in SO.
Http Basic Authentication in Java using HttpClient?
I'm trying to set up a basic website (serverless on AWS) that would allow visitors to login with Google and/or Facebook. Currently I'm planning to use S3, Cognito with Federated Identities, API Gateway, Lambda (NodeJS), with DynamoDB. The client app will be using Angular.
I have the social login with Google and Facebook working, and currently I am inserting a row in a "users" table when a user logs in the first time that includes the cognitoId, name, profile picture URL, etc.
I also figure it would be a good design to store the user's information with their email address as the key, instead of something like the cognitoId so that the user can login using different Providers and see the same data. So I need to know the authenticated user's email address, but I figure it should come from Cognito and not straight from the user (since the client app shouldn't be trusted).
I believe that Cognito is storing the user's email address because I have enabled that field as required int the User Pool.
The issue I'm having is that I cannot find any information about how to get the user's email address from Cognito.
The closest that I've come is this post, but I can't find the access token anywhere: How to get user attributes (username, email, etc.) using cognito identity id
This post indicates that I may be able to use GetUser, but I again don't know where the AccessToken comes from: creating user using AWS cognito identity
If I do need to use GetUser and the AccessToken, where does it come from, and how do I generate it? Does it come from the client, or can I get it in Lambda using AWS.config.credentials?
I've been trying to figure this out for a while now and I'm feeling like I'm missing something really simple!
Firstly, go into Cognito Identity provider (in the Cognito console) and make sure your provider "Authorize Scope" is suitable. For example if you clicked on the Google provider your Authorize scope might be "profile email openid". The scope will vary by provider, but whatever scope you are using, it must provide access to the users email.
When your user logs in with an external identity provider (lets say Facebook), Cognito negotiates with Facebook and then calls your Callback URL, which is set in the 'App Client Settings' part of the Cognito console. That Callback contains a parameter called 'code' - the parameter is set in the URL of the Callback made my Cognito. The code is an OAuth token.
Now you have an OAuth token in your client you need to POST that to the AWS Token Endpoint. The token endpoint returns three new tokens in the response; a JWT ID Token, a JWT Access Token and a refresh token. Take the "id_token" attribute from the endpoint response. Parse that id_token as a json string, and take the 'email' element. Now you should have the users email address.
Here is my working example in Java. This is a servlet that gets called by the Cognito Callback.
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper;
import com.nimbusds.jwt.SignedJWT;
import net.minidev.json.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
public class CognitoLandingServlet extends HttpServlet {
static final Logger LOG = LoggerFactory.getLogger(CognitoLandingServlet.class);
private static final long serialVersionUID = 1L;
public CognitoLandingServlet() {
super();
}
#Override
protected void doGet(final HttpServletRequest request, final HttpServletResponse response)
throws ServletException, IOException {
// Get the OpenID Connect (OAuth2) token passed back from the hosted Cognito
// Login Page
final String code = request.getParameter("code");
LOG.debug(String.format("Cognito OAuth2 code received from Cognito: %s.", code));
if (code != null) {
// do nothing, we have a code as expected
} else {
LOG.debug(String.format(
"Landing page requested without a Cognito code, the request probably didn't come from Cognito"));
// we dont have a token so redirect the user to the application sign in
// page
request.getRequestDispatcher("/signin").forward(request, response);
}
// Exchange the OIDC token for Cognito Access and ID JWT tokens using AWS
// Token
// Endpoint
// There does not appear to be a Java SDK to handle this :(
final String cognitoClientId = System.getProperty("CognitoClientId");
final String redirectUri = System.getProperty("CognitoCallBackUrl");
final String awsTokenEndpoint = System.getProperty("AwsTokenEndpoint");
final String jwt = swapOauthForJWT(cognitoClientId, code, redirectUri, awsTokenEndpoint);
// Complete the login using the JWT token string
loginWithJWT(jwt, request, response);
}
#Override
protected void doPost(final HttpServletRequest request, final HttpServletResponse response)
throws ServletException, IOException {
}
private void loginWithJWT(final String jwtString, final HttpServletRequest request,
final HttpServletResponse response) {
final JSONParser parser = new JSONParser();
SignedJWT signedIdJWT;
try {
// Take the id token
final JSONObject json = (JSONObject) parser.parse(jwtString);
final String idToken = (String) json.get("id_token");
// Access token is not currently used
// String accessToken = (String) json.get("access_token");
// Process the id token
signedIdJWT = SignedJWT.parse(idToken);
final String userId = signedIdJWT.getJWTClaimsSet().getSubject();
// Start NEW Session and start adding attributes
final HttpSession session = request.getSession(true);
session.setAttribute("userId", userId);
final String cognitoUsername = (String) signedIdJWT.getJWTClaimsSet()
.getClaim("cognito:username");
if (cognitoUsername != null) {
user.setUserName(cognitoUsername);
session.setAttribute("username", cognitoUsername);
}
final String email = (String) signedIdJWT.getJWTClaimsSet().getClaim("email");
if (email != null) {
user.setEmail(email);
session.setAttribute("email", email);
}
// Save the user to a database (code removed for stack overflow)
//request.getRequestDispatcher("/dashboard").forward(request, response);
response.sendRedirect("/dashboard");
LOG.info(
String.format("A user with userid %s and email %s successfully signed in", userId, email));
} catch (final java.text.ParseException e) {
LOG.error(
String.format("The JWT token could not be parsed by JOSE library. %s", e.getMessage()));
} catch (final ParseException e) {
LOG.error(String.format("The JWT token could not be parsed by JSON simple library. %s",
e.getMessage()));
} catch (final IOException e) {
LOG.error(String.format("Failed to request webpage at the end of the login process - io. %s",
e.getMessage()));
}
}
private String swapOauthForJWT(final String cognitoClientId, final String oauthCode,
final String redirectUri, final String awsTokenEndpoint) throws IOException {
// Build the URL to post to the AWS Token Endpoint
final String urlParameters = String.format(
"Content-Type=application/x-www-form-urlencoded&grant_type=authorization_code&client_id=%s&code=%s&redirect_uri=%s",
cognitoClientId, oauthCode, redirectUri);
LOG.debug(String.format("User is swapping OAuth token for a JWT using URL %s", urlParameters));
final URL url = new URL(awsTokenEndpoint);
final URLConnection conn = url.openConnection();
conn.setDoOutput(true);
final OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
writer.write(urlParameters);
writer.flush();
// Read the data returned from the AWS Token Endpoint
final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
final StringBuilder responseStrBuilder = new StringBuilder();
String inputStr;
while ((inputStr = reader.readLine()) != null) {
responseStrBuilder.append(inputStr);
}
// Close the connection
writer.close();
reader.close();
LOG.debug(String.format("Finished swapping OAuth token for a JWT"));
return responseStrBuilder.toString();
}
}
You also need to add Attribute mappings in your user pool. Check if you have forgotten to add the mappings. You can find "attribute mappings" tab under "federation" inside your User Pool settings
To get the email, you have to request it to the identity provider (facebook, google, user pool).
To get the email from the user pool you have to do something like:
cognitoUser.getUserAttributes(function(err, result) {
if (err) {
alert(err);
return;
}
for (i = 0; i < result.length; i++) {
console.log('attribute ' + result[i].getName() + ' has value ' + result[i].getValue());
}
});
Cognito Identity doesn't save the emails.
I have implemented an MVC Application running with Sitecore. The Startup class of OWIN have implemented following like that:
[assembly: OwinStartupAttribute(typeof(WebApplication1.Startup))]
namespace WebApplication1.Web
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
}
public void ConfigureAuth(IAppBuilder app)
{
app.CreatePerOwinContext<AppIdentityDbContext>(AppIdentityDbContext.Create);
app.CreatePerOwinContext<AppUserManager>(AppUserManager.Create);
app.CreatePerOwinContext<AppRoleManager>(AppRoleManager.Create);
app.UseOAuthBearerTokens(new OAuthAuthorizationServerOptions
{
Provider = new AppOAuthProvider(),
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/Authenticate")
});
}
}
}
I have expected when I submit a username, password and grant_type value is password with method POST into URL http://<>/Authenticate the token bearer return to allows user can log in. Unfortunately, the Sitecore throw content is not found and I cannot figure out the way let the request going to the OWIN Middle Authorization. How can I sort it out?
So I have an app set up, and I'm trying to send scores via a server rather than from the application. This allows me to keep scores longer term, whilst also having the social advantages of Facebook.
Now, the problem I have comes in retrieving the scores using the Application Token. I can post absolutely fine using either the Application Token or a User Token, but when retrieving the scores with the Application Token I receive the following:
{
"data": [
]
}
If it was flat out not working or a permissions issue I'd expect to receive an error returned, but the fact it returns an empty array is puzzling. More puzzling is that using a User Access Token retrieves the score absolutely fine, so it's clearly arriving correctly into the Facebook backend.
Is this just a problem with using an App Access Token in this situation? The documentation says that I should be able to use one, but maybe it's mistaken?
I'd also like to clarify that I've run this both in code and via the Graph Explorer, always with no success.
Make sure that you have granted user_games_activity and friends_games_activity permissions
on developers.facebook.com/tools/explorer
from above link you will get an application access_token and add it in your code like this
public void sendDataToFacebookGraphServer()
{
// TODO Auto-generated method stub
final Session session = Session.getActiveSession();
List<String> permissions = session.getPermissions();
if (!isSubsetOf(PERMISSIONS, permissions)) {
Session.NewPermissionsRequest newPermissionsRequest = new Session
.NewPermissionsRequest(UnityPlayer.currentActivity, PERMISSIONS);
session.requestNewPublishPermissions(newPermissionsRequest);
return;
}
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("https://graph.facebook.com/user_id/scores");
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("score", "3000"));
// add this line and try
pairs.add(new BasicNameValuePair("access_token", "add_app_access_token_here"));
try{
post.setEntity(new UrlEncodedFormEntity(pairs));
}
catch(UnsupportedEncodingException e)
{
}
try{
response = client.execute(post);
Log.i("*********Response*******************************************************", response.toString());
UnityPlayer.currentActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Toast.makeText(UnityPlayer.currentActivity,""+response.toString(),Toast.LENGTH_LONG).show();
}
});
}
catch (IOException e1)
{
}
}
Is this supposed to work with the app access token? I don't think it is.
According to the Scores Documentation you can
Retrieve a user's score with the user or app access token (/USER_ID/scores)
Retrieve a user's friends' scores for your app with the user access token (/APP_ID/scores)
Retrieve a user's friends' scores in any app with the user access token (/USER_ID/scores) - though this one respects those users' privacy settings so you won't get an answer for users whose game/app activity is private