ServiceStack Jwt authentication check if authenticated - session

I need to allow anonym access endpoint but still check if user is authenticated then give some extra data.
using [Authenticate] attribute I can use
var session = SessionAs<AuthUserSession>();
and then session.IsAuthenticated
it works just fine but without [Authenticated] attribute session is empty(new session is generated with new id and all props is not populated with user data)
How to check if user is authenticated without [Authenticate] attibute with request which uses jwt token?

The JwtAuthProvider is an IAuthWithRequest provider which only validates the JWT Token and returns the appropriate HTTP Error Response if the token is invalid when it needs to Authenticate the the Request, e.g. when Services annotated with the [Authenticate] attribute. If Services don't require Authentication, the IAuthWithRequest Auth Providers and JWT Bearer Tokens aren't validated and the Users Session isn't automatically populated.
But in the latest v4.5.9 that's now on MyGet new APIs have been added to JWT AuthProvider to be able to create custom JWT Tokens and convert them into User Sessions, specifically you can create a UserSession from a JWT Token with:
var session = JwtAuthProvider.CreateSessionFromJwt(base.Request);
Which is just a helper for resolving the registered JwtAuthProviderReader and calling its ConvertJwtToSession() API:
var jwtProvider = (JwtAuthProviderReader)
AuthenticateService.GetAuthProvider(JwtAuthProviderReader.Name);
var session = jwtProvider.ConvertJwtToSession(base.Request, base.Request.GetJwtToken());

Related

How to enrich JWT in spring authorization server?

I have a SAAS server with microservice architecture. Authentication is done by the new Spring authorization server. For some domain situation, I want to be able to re-issue a JWT for a logged-in user without forcing the user to enter their password again to enrich their token with additional claims.
Having: Logged-in user with claim set A.
Required: Create a new token for the user with claim set B. (Without user intervention)
I'm looking for something like this:
#PostMapping("/renew")
public Authentication token() {
return jwtAuthenticationProvider.authenticate(
new BearerTokenAuthenticationToken(JwtUtil.getCurrentAuthenticationTokenValue())
);
}
Where JwtUtil.getCurrentAuthenticationTokenValue() extracts logged-in user token value from SecurityContextHolder. This setup creates no new token and returns the old one like no authentication process has been triggered.
But I cannot find a function/service that generates a new token in spring authorization server.
PS. I cannot use RefreshToken to get new AccessToken because my client is public and according to this, RefreshToken only is issued for confidential clients.
You can read about OAuth2TokenCustomizer in the docs. Here's an example of customizing the access token:
#Bean
public OAuth2TokenCustomizer<JwtEncodingContext> tokenCustomizer() {
return (context) -> {
if (OAuth2TokenType.ACCESS_TOKEN.equals(context.getTokenType())) {
context.getClaims().claims((claims) -> {
claims.put("claim-1", "value-1");
claims.put("claim-2", "value-2");
});
}
};
}
In your case, you could issue a new request to the authorization endpoint (e.g. GET /oauth2/authorize?...) from the client to begin the authorization_code flow with different scopes or additional request parameters and use the customizer to add whatever claims you need. Based on the information you've provided, this would be the recommended way to use the authorization server to issue new tokens.
Adding custom endpoints to perform OAuth2-related actions (such as a custom /renew endpoint) without incorporating best practices and standards from the specification(s) would not be recommended.

Does Passport utilize guards not to authenticate users but to validate access tokens on routes where these tokens are required?

I'm a little bit confused by the documentation. It's said:
Passport includes an authentication guard that will validate access
tokens on incoming requests. Once you have configured the api guard to
use the passport driver, you only need to specify the auth:api
middleware on any routes that require a valid access token.
So it means that Passport utilizes guards not to authenticate users but to validate access tokens on routes where these tokens are required. Did I get that right?
In this case, validating the access token is authenticating the user. To understand why this is the case, let's walk through a simplified authentication flow using JWTs (let's ignore oAuth2 for a bit).
The user is logging in on the website. This triggers a POST /login request, with the username and the password in the request body.
The backend validates the users credentials. If the credentials are valid, it will issue a JWT, which will act as an access token. The JWT payload will contain some data that allows the backend to identify a user, e. g. the user id. The JWT then is signed with a secret that only the backend knows.
The backend will return the access token to the client, who has to include the access token in any subsequent requests to the server. Usually, the client will provide the token in the Authorization header.
When handling the next request from the client, the backend will extract the access token from the Authorization header and check its signature. If the signature is valid, the backend can be sure that the token data has not been manipulated, e. g. by changing the user id on the access token. With a valid signature, the backend can extract the user id from the tokens payload and set the User model for that specific id as authenticated. With an invalid signature, the backend will probably return something like 401 Unauthorized.

AWS Cognito: Add custom claim/attribute to JWT access token

My app creates a custom attribute "userType" for each new signed-up user. Now I would like this "userType" claim/attribute to be added to the JWT access token whenever the user signs in or the token gets refreshed.
Is there an option to tell cognito to add my custom claim/attribute to the JWT access token? (Without a pre token generation Lambda)
Custom attributes are not available in Cognito access token. Currently it is not possible to inject additional claims in Access Token using Pre Token Generation Lambda Trigger as well. PreToken Generation Lambda Trigger allows you to customize identity token(Id Token) claims only.
You can use ID token to get the token with custom attributes.
Access tokens are not intended to carry information about the user. They simply allow access to certain defined server resources.
You can pass an ID Token around different components of your client, and these components can use the ID Token to confirm that the user is authenticated and also to retrieve information about them.
How to retrieve Id token using amazon cognito identity js
cognitoUser.authenticateUser(authenticationDetails,{
onSuccess: function(result) {
var accessToken = result.getIdToken().getJwtToken();
console.log('accessToken is: ' + accessToken);
},
onFailure: function(err) {
alert(err.message || JSON.stringify(err));
},
});
I have the same problem when I want to create several microservice. There isn't a way I can customize an access token, but only an identity token. However, I use client credentials in the machine-to-machine which needs access token. So, in no way I can customize my token. At last, I decide to add such info(like user type) in the event header. It's not a very secure way compared to customize a token, but there isn't any other easy way to do it right now. Otherwise, I have to rewrite the authorizer in Cognito. Like rewriting a customize authorizer and it's very painful.
I have the same issue with Cognito; exist other tools like "PingFederate"Auth-server of Ping identity and Auth0 Auth-server; I know that the requirement isn't part of the standard, but these applications were my alternatives to fix this issue
The responses suggesting to use the ID Token for authorization in your backend systems are bad security practice. ID Tokens are for determining that the user is in fact logged in and the identity of that user. This is something that should be performed in your frontend. Access Tokens on the other hand are for determining that a request (to your backend) is authorized. ID Tokens do not have the same security controls against spoofing that Access Tokens have (see this blog from Auth0: https://auth0.com/blog/id-token-access-token-what-is-the-difference/).
Instead, I recommend that your backend accept an Access Token as a Bearer token via the Authorization HTTP header. Your backend then calls the corresponding /userinfo endpoint (see: https://openid.net/specs/openid-connect-core-1_0.html#UserInfo) on the authorization server that issued the Access Token, passing such said Access Token to that endpoint. This endpoint will return all of the ID Token information and claims, which you can then use to make authorization decisions in your code.

JWT + Laravel Socialite with OAuth Parameters

What I want to achieve:
Safely allow users to connect their accounts to different social medias using a Single Page Application.
What I am doing:
I am using an SPA and therefor utilizing JWT as my user authentication method. I am passing the JWT token in the OAuth call with Laravel Socialite like this:
return Socialite::driver($provider)
->with(['provider' => $provider, 'token' => $token])
->redirectUrl($redirectUri)
->stateless()
->redirect();
On the callback I get the user based on the token. Using this method allows the third party provider to get access to the JWT token. Which is very unsafe.
My Question(s):
Is there any better way to do this? Should I use some kind of hash + salt + secret?
You should check the JWT.
JSON Web Tokens are an open, industry standard RFC 7519 method for
representing claims securely between two parties.
JWT Token composes of three parts, header, payload and verify signature.
You are using stateless authentication and the only way to authenticate the user is by the JWT Token. To authenticate the user after redirect, you should create a payload containing application's user id, and pass to the third party provider, so that when redirect, they will pass the JWT token back to you.
It is no problem to pass the JWT Token to third party provider, but be aware that the payload should not contain any sensitive data. If the payload is somehow sniffed, it will not have any harm because, if hacker is trying to change the payload, the verify signature helps and the application cannot verify the token and the application will throw exception.
The signature is used to verify that the sender of the JWT is who it
says it is and to ensure that the message wasn't changed along the
way.

Spring boot webapp as client of Google Oauth2

I'm writing a webapp using Spring Boot. For my project, I need to connect to Google for retrieving calendar information about users.
So, I integrate Spring security Oauth2 for user connection and after I want to use the Google calendar API.
The connection is ok and after it, Google redirects to a page of my webapp defined by this controller:
#Controller
class ConnectedController {
private String token
#RequestMapping("/welcome")
String welcome(Principal principal,
Model model) {
OAuth2Authentication auth = principal
model.addAttribute("user", auth.userAuthentication.details)
// credential
def api = new CalendarApi()
token = auth.details.tokenValue
println "Token: [$token]"
api.fetch(token)
return 'welcome'
}
}
For the Calendar API, I need the access token value and the refresh token value. I find the access token value in the principal object but where is the refresh token?
For information, I configured the authorization like below to have the resfresh token (normally):
userAuthorizationUri: https://accounts.google.com/o/oauth2/v2/auth?access_type=offline&prompt=consent
As I interpret the google Oauth2 doc you get a authorization code when consent is given by the user. And this code should be used to get an access token and a refresh token from the API.
The result is an authorization code, which the application can
exchange for an access token and a refresh token.
Have you tried this?

Resources