I am using AmazonCognitoIdentityProviderClient SDK.
I am trying to get a custom attribute for user in cognito. from c# front end i am passing username , password and email id. is there any function to retrieve the user atribute from cognito ?
After Cognito successfully authenticates a user in your pool, you will receive several JWTs - an access token, an ID token, and a refresh token. These tokens can be accessed in the authentication result object that is returned by the SDK (InitiateAuthResponse).
You can verify and decode the ID token to unpack the claims about the user's identity. This will also include any custom attributes you have defined on your User Pool. For .NET you can use JwtSecurityTokenHandler to decode the JWT (Sytem.IdentityModel.Tokens.Jwt namespace). After decoding the token, access the Claims property to get the user information. Custom attributes are prefixed with custom:, while Cognito attributes (such as username) are prefixed with cognito:.
Here's an AWS doc on how to decode the token: https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-using-tokens-verifying-a-jwt.html
Here's an example on how to use JwtSecurityTokenHandler: https://www.jerriepelser.com/blog/manually-validating-rs256-jwt-dotnet/
You can also use the Access Token to use the SDK to lookup a user directly, and the response from the AWS SDK will include the user attributes. Here's the doc on that: https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_GetUser.html
Try Amazon.CognitoIdentityProvider.AmazonCognitoIdentityProviderClient.GetUserAsync(), it will return all standard and custom attributes. Please note that the method will only return the attributes for which a value is set.
Related
I'm developing an .NET Web API and using JWT tokens to secure it. In my research of the best way to implement it, i decided to use the jwt claims to also limit the access to content, depending on specific claims present on the token. I can now manually verify if for example, a userId matches with the userId of a record's userId and return it if it's a match, but this is very tedious and not quickly adds up the amount of code just to do the same task...
Is there a way to implement something like an action filter to apply the claims to every request and return only the records that match the information in the token?
Thanks everyone in advance
See this implementation on this project.
https://github.com/cuongle/WebApi.Jwt/blob/master/WebApi.Jwt/Filters/JwtAuthenticationAttribute.cs
It's a simple scenario.
JWT contains a user's id or some claims.
You have a WEB API endpoint like ("GetCurrentUserData()") decorated with your custom ActionFilterAttribute.
Within that method you will call a helper function that will read the current request user claims and return them in a simple form (like user id).
See: Get claims from a WebAPI Controller - JWT Token,
Then within the method you can query/filter your returned data based on the Id/Claims of the current user of the request.
I have a web app which uses the Xero.NetStandard.OAuth2Client package to allow for authentication with Xero.
Once the user is redirected back into my app, I use the IXeroClient.RequestAccessTokenAsync method to exchange their code for an IXeroToken object, which allows me to make calls against the Xero API, as expected.
The one thing I do not know how to do, and which I can't seem to find in the official documentation, is how do I extract the user's details (namely their name and email address) from the IXeroToken object.
As per the standard, the information is encoded as JWT string in the IdToken property, but I am not sure how I am meant to get the information out of it without an additional dependency.
The built in System.IdentityModel.Tokens.Jwt.JwtSecurityToken class can deserialize the IdToken payload.
new JwtSecurityToken(accessToken.IdToken).Claims contains all the claims in the token.
The relevant types are:
email - The user's email
xero_userid - The user's id (guid)
given_name - The user's first name
family_name - The user's last name
The claims' existence is obviously conditional to the appropriate scope being set.
I have a resource (REST) server (written in Java/Spring) that I need to validate a Microsoft token from a client. I need to:
Check that the token is valid for my app
Get the token's email address and lookup that user in my app (I can do this)
I currently use Google, Facebook and am adding Windows auth.
For Google, I check my token at:
https://www.googleapis.com/oauth2/v3/tokeninfo?access_token={accessToken}
For Facebook, I use:
https://graph.facebook.com/debug_token?input_token={accessToken}&access_token={appId}|{appSecret}
What do I use for live?
https://apis.live.net/v5.0/????
I need something that returns my app id so I can make sure the token was created by my app.
I can get the user info from the token just fine (the URL is https://apis.live.net/v5.0/me?access_token={accessToken}) but it does not allow me to verify that the user is for my app that is registered.
What is the token validation scheme here? It's not a JWT token, because it does not have any '.' characters in it...
According to this https://developer.microsoft.com/en-us/graph/docs/concepts/auth_overview:
Access tokens issued by Azure AD are base 64 encoded JSON Web Tokens (JWT).
However, when I try to base64 decode my token, it is binary. https://apis.live.net/v5.0/me shows that it's a valid token, though.
Here is an expired token:
EwAwA61DBAAUcSSzoTJJsy+XrnQXgAKO5cj4yc8AAfD7xbB6agxt1xZJhCeONQNzKUS97NgwifhSev98+2Boa/kdgnR/hk6KzNBiFz0mNsPWQrEhTsQRbta9QyGGezyVhpYLtMbWbWHUhNh/lY3w31x/5yeuUmw/ITXwu7Qk3L8t3ESzYoy9NCJT7AzkFHf6hUgDg5lNeFbwZD5mFe3Y6NH3p3kYHDBJwDHO7VN+AlTCWc3z1n06NSxQOisOjZYZ3YrWhdaffMZ9yaBfRYcSLvBLeA8u//jfhIdunfPXQyaXnNEHp3GAlVASPcskQnRmZHIz9IcqE9ZZPpXNHcgz36UIKV1aqkDGnYIqzDsAqvmICN3tWJhrabFfPC00yUIDZgAACM68oajVfXdPAAKTFEdhizTgVDOWT7yytFJCHesQFy3yfKiJ+/lANntrgT0peCZt6cHsS1iqdF7A3WMhFc4hQP7kV29PCPTouLyNj8Ygcnl024H3usPbBqCqDrRsNNjJAdKkR2Cni9Kchw/i02NfC+DUy2LmUBTb5oHZXG7zx21K+l/HBbOUn0VRb4l+rsx7CTiabu1s3cdCrmhDDuIwWv2W8Id6Y6VBYs6zddHRY58B1YRZSQevcsT05xehrebS40E+Pyy/Z9vJXb2FTM+pY1+HvtPpxqxqn73Bp3wX1A8YH8Lbe4J/J+aHbE6mEnEvQMiavB0nrh0gTAydrBkkWuY3zbuQaQFE96/i3yWad8j0A0cU8/YquXFBo6k1oD0dWOKNOQ9x+Dad7W3yFEB2gF9jZtxU5OdV4S3uRmdqyaj2kGVI2eVrX4/13f97tKA3a2ZIF7ZUZKgpwNybOrz9COAilxZvr3Z+X1jTdTYOXWMs8tuOOpru2g64sZUzgtj0JETWJcHfg9yLC72DSaAFzDR/KRa2u+C7XGaywIPEqoUs/4iRaLc5RPtdRlLHCp0rgmIlMc0/iwR7K6N2Q5odVP7QzxlBNtGW51iHNCFgRDrQ8zNkv2hdexxt7Of2i+lqe2N3Z3ENUoQa6SRBYzFDPOka+Mr5qWVxeMeulYmXFkBh0NyKaLJIqrkSMy0C
I have a Web API with authentication enabled (bearer token). This is called by a client application and I want to protect it from anonymous usage so I would like to create a single user and create a bearer token for it.
I can create the token by calling the register and token methods, but I would like to do this from code.
As far as I know, the bearer token is not stored in the database. Can it be retrieved somehow using the ASP.NET Identity API?
I would also like to create this user from code and save the token somewhere because I need to deploy the database to multiple servers.
I do not recommend going with this approach if you have only one client who will talk to your API, my understanding that you need to issue a very very long lived access token maybe for a year and keep using this token to access the back-end API, right?
What you will do if this token is stolen? You can't revoke the access token, so it is somehow like your master key (password).
My recommendation is to use OAuth refresh tokens along with access tokens. This depends on the type of your client, you can check how this is done here http://bitoftech.net/2014/07/16/enable-oauth-refresh-tokens-angularjs-app-using-asp-net-web-api-2-owin/
The refresh tokens can be revoked and they can expire after a very long time. Let me know if you need further details to implement this.
Create a Custom Authentication Attribute and store the token hashes for users. A user can have multiple tokens. Then you can let user do what he wants - log out all other sessions when password is changed or remove sessions selectively
public class CustomAuthAttribute : System.Web.Http.AuthorizeAttribute
{
protected override bool IsAuthorized(HttpActionContext context)
{
var accessToken = HttpContext.Current.Request.Headers["Authorization"];
var hash = accessToken.Md5();
//store the hash for that user
//check if the hash is created before the password change or its session was removed by the user
//store IP address and user agent
var isBlackListed = ...
.....
return !isBlackListed && base.IsAuthorized(context);
}
}
If you're needing to decode the token within a WebAPI Controller function, I found this worked:
String token = Request.Headers.Authorization.Parameter;
Microsoft.Owin.Security.AuthenticationTicket t = Startup.OAuthOptions.AccessTokenFormat.Unprotect(token);
I have created a project that uses DotNetOpenAuth to implement both an OAuth2 AuthorizationServer and ResourceServer in one.
What I am wanting to do is use the OAuth as pseudo-authentication where the Client is authorised by OAuth to get the associated resource which is the user's profile.
On the ResourceServer I can use resourceServer.VerifyAccess( request, out result );
to successfully return the IPrincipal.
My question is: on the ResourceServer (which is the same as the Authorization Server) how can I get the user/user id/user profile from the Principal (or anything else that I have access to). The Principal name looks like a base64 encoded string. But that doesn't seem to match anything else that I have access to.
DotNetOpenAuth's ResourceServer.VerifyAccess method gives you a principal whose name is the user who authorized the access token, and whose roles are the scopes that were granted to that token.
If you're seeing some base64 encoded string looking thing as the principal's name, it sounds like you should double check your code. I suggest you start at the point in your authorization server code that you call AuthorizationServer.PrepareApproveAuthorizationRequest passing in the authorizing username. Make sure that's what it should be.
It's highly unlikely that it was corrupted in transit because the token is encrypted and signed.