JWT Auth and Flutter : How to access a single model data - flutter

I have an API with JWT Authentication enabled. I am trying to login a user and then update the user data. In JWT Auth, after login the server provides a token which is needed to update the user data. Now I can login a user and the server is giving me a token. I converted the token into LoginResponseModel.
These are the response model:
class LoginResponseModel {
String token;
String userNicename;
LoginResponseModel({this.token, this.userNicename});
factory LoginResponseModel.fromJson(Map<String, dynamic> json) {
return LoginResponseModel(
token : json['token'],
userNicename : json['user_nicename'],
);}
}
Although I can insert the token into model, I cannot access the token from my APIService class creating a LoginResponseModel class instance.
My approach of accessing the token is something like this:
LoginResponseModel loginResponseMode;
String token = loginResponseMode.token
var dio = Dio();
dio.options.headers["Authorization"] = "Bearer $token";
// here is my network call code
But here i got null value of token. Would you please help me out how to access only the token from LoginResponseModel ? Thank you.

Related

Signed in to Cognito with Amplify SDK, where is JWT?

In my Vue application, I did
import Amplify, { Auth } from 'aws-amplify'
...
Vue.prototype.$Auth = Auth
in main.js, and then
const user = await this.$Auth.signIn(this.userInput.email, this.userInput.password)
console.log(user)
in my login component. The console.log prints
Where is the JWT here?
The problem was I hadn't created a new password yet. This is done with a
Auth.completeNewPassword(user, '<new-password>')
where user is the CognitoUser object returned from Auth.signIn.
After this, when doing signIn again, the signInUserSession field of the CognitoUser will contain the access token under user.signInUserSession.accessToken.jwtToken.

Servicestack Session is null only when using JWT

This fails on SessionAs in the baseservice in Postman when I authenticate via JWT. But when I use Basic Auth it works fine. Anyone know why?
Apphost
Plugins.Add(new AuthFeature(() => new CustomUserSession(),
new IAuthProvider[]
{
new BasicAuthProvider(), //Sign-in with HTTP Basic Auth
new JwtAuthProvider(AppSettings) {
AuthKeyBase64 = AppSettings.GetString("jwt.auth.key"),
RequireSecureConnection = false,
}, //JWT TOKENS
new CredentialsAuthProvider(AppSettings)
})
{
BaseService
public class ServiceBase: Service
{
public IUserAuth UserAuth
{
get
{
var session = SessionAs<AuthUserSession>();
return AuthRepository.GetUserAuth(session.UserAuthId);
}
}
}
Your SessionAs<T> needs to match the UserSession Type registered in the AuthFeature plugin which is CustomUserSession.
ServiceStack's JwtAuthProvider populates the UserAuthId in the JWT's sub JWT Payload so you should check the Raw HTTP Headers to make sure the JWT Token is being sent, either in HTTP's Authorization Header as a BearerToken or in the ss-tok Cookie. If it is being sent you decode the JWT sent in https://jwt.io to make sure it contains a valid payload, in this case it contains a "sub" property in the JWT payload containing the UserAuthId of the user being authenticated.

IdentityServer3 Guidance Needed

I have a scenario where a client has an OpenIdConnect (OIDC) token in their possession. The OIDC was issued from an external OIDC provider, I am not the OIDC provider, just the downstream consumer of it.
The goal is for the client to exchange said OIDC Token, for temporary credentials, or an accesstoken, which will then give them api access to more specific resources.
In my case, the OIDC represents a user. The client, has a ClientId/Secret, which is used to establish service-2-service trust. In the end I would like to have something that looks a lot like the CustomGrant token Request.
static TokenResponse GetCustomGrantToken()
{
var client = new TokenClient(
token_endpoint,
"custom_grant_client",
"cd19ac6f-3bfa-4577-9579-da32fd15788a");
var customParams = new Dictionary<string, string>
{
{ "some_custom_parameter", "some_value" }
};
var result = client.RequestCustomGrantAsync("custom", "read", customParams).Result;
return result;
}
where my customParams would contain the OIDC to my user.
Problem: I can get a token back from the GetCustomGrantToken call, however a follow up Webapi call fails to pass Authorization. i.e. Identity.isAuthenticated is false.
The it all works fine if I get a clientcredential token.
static TokenResponse GetClientToken()
{
var client = new TokenClient(
token_endpoint,
"silicon",
"F621F470-9731-4A25-80EF-67A6F7C5F4B8");
return client.RequestClientCredentialsAsync("api1").Result;
}
Had the CustomGrantToken worked I would have put my users account info in the claims, thus giving me context in the subsequent WebApi calls.
Any direction would be appreciated.

Authentication for Azure REST Api

I want to communicate with Azure only with REST Api and without any sdk component - communicate to the new ARM
how can I get the Bearer token for the authentication? i saw that all the examples use the SDK for that
To get a token for authorization, you need to install the Active Directory Authentication Library into your project. The easiest way to do this is to use the NuGet package.
Use this code to get the token:
public static string GetAToken()
{
var authenticationContext = new AuthenticationContext("https://login.windows.net/{tenantId or tenant name}");
var credential = new ClientCredential(clientId: "{application id}", clientSecret: {application password}");
var result = authenticationContext.AcquireToken(resource: "https://management.core.windows.net/", clientCredential:credential);
if (result == null) {
throw new InvalidOperationException("Failed to obtain the JWT token");
}
string token = result.AccessToken;
return token;
}
There are more details and code examples at Authenticating Azure Resource Manager requests.

Facebook4J support for exchanging access-tokens

I'm looking for a way to exchange short-lived access tokens for long-lived access tokens in our backend as described by Facebook here. How to do this with facebook4j?
I have done something like this to exchange old token for new token:
private AccessToken refreshToken(Facebook facebook, AccessToken currentToken) throws Exception {
String clientId = configuration.getString(ConfigurationKeys.SOCIAL_FACEBOOK_CLIENTID);
String clientSecret = configuration.getString(ConfigurationKeys.SOCIAL_FACEBOOK_CLIENTSECRET);
Map<String, String> params = new HashMap<String, String>();
params.put("client_id", clientId);
params.put("client_secret", clientSecret);
params.put("grant_type", "fb_exchange_token");
params.put("fb_exchange_token", currentToken.getToken());
RawAPIResponse apiResponse = facebook.callGetAPI("/oauth/access_token", params);
String response = apiResponse.asString();
AccessToken newAccessToken = new AccessToken(response);
facebook.setOAuthAccessToken(newAccessToken);
return newAccessToken;
}
I think this can be done after each login so the access token is refreshed even if it still valid - you will just get newer token with 60 days of validity.
What do you think?
I am extending the Facebook class. The method they provided don't work. So I wrote another function which does gives a long lived token but it's somehow invalid ( I tried testing the new token with token_debug and tried to generate client_code with it)! I will update you if I get to work it out. If you can solve it, please update me.
Please remember I didn't clean up the code as I am still writing on it.
public function GetExtendedAccessToken()
{
//global $CONFIGURATIONS;
//$info=$this->api($path,'GET',$args);//doesn't work as api overrides method to post
$string=file_get_contents("https://graph.facebook.com/oauth/access_token?client_id=".$this->getAppId()
."&client_secret=".$this->getAppSecret()
."&fb_exchange_token=".$this->getAccessToken()
."&grant_type=fb_exchange_token"
."&redirect_uri=".$redirectUri);
var_dump($string);
$tokenInfo=explode('&',$string);
$exAccessToken=str_replace('access_token=', '', $tokenInfo[0]);
$expiresAt=str_replace('expires=', '', $tokenInfo[1]);
echo "expires in ". (time()-$expiresAt);
var_dump($exAccessToken);
return $exAccessToken;
}
It works now. Some times I get an error for not providing redirect_uri.