Authorization Header in SignalR 2.0 - authentication

I am using WebApi and token based authentication for my api controllers.(Authorization :bearer xyzabc..) I now have a signalR hub and would like to authenticate clients by the same token they have on the client side.
How would i do that ? This link shows how to send token through url parameter, but i am not sure how i can use that token and authenticate the user on server side.

I solved this by passing the token as a parameter of my Hub method instead of header. but i imagine it is possible to do it using headers too (just extracting the token from Context.Headers or something).
Either way, after getting the token in your hub method, just use this code.
public Task SendMessage(string message, string token)
{
var ticket = Startup.OAuthOptions.AccessTokenFormat.Unprotect(token);
bool isAuth = ticket.Identity.IsAuthenticated;
//You can retrieve other details like username and userid from ticket
...rest of your code..
}

I wouldn't send the token every time. I'd establish your context user principal on the OnConnected virtual method and read from a query string passed from a token.
In my case. I just created an abstract class that inherited from the Hub class and then stuffed my oauth claims generation logic there. Then my regular concrete hubs just inherited from my base custom hub class.
Another option would be to use either a custom authorize attribute or another hub pipeline module.
I think these tactics might keep your code DRY and extendable.

I've discovered that when you call the default /Token handler from Web API from something like JQuery, the browser is also sent a cookie which is used to authenticate you with SignalR.
You ought to be able to use the [Authorize] attribute as well as "Context.User.Identity" in your SignalR hub methods to get the current user as long as you've called /Token with valid credentials from the browser before connecting to the hub.

Related

Getting refresh_token server-side (sessionToken) with Okta

We wish to use our own httponly strict cookie with access and refresh token in it for our microservices architectures.
We are primary using OKTA Authentication API to log users with our own custom Sign-in page.
We were able to get the access_token on the authorize endpoint using the responsetype=token with sessionToken and redirecting the result as a form_post on our back-end endpoint.
I was unable to retrieve the refresh_token despite adding the offline_access in the scope even if it is checked in my okta application setting.
I don’t want to use resource password flow since we prefer using sessionToken which will work with multi factor if needed in the future.
I also try using the code flow and redirecting the result on our back-end but since the code flow is client-side it’s return this error "PKCE code verifier is required when the token endpoint authentication method is ‘NONE’." This error occur even if we choose a .NET application
How can we retrieve the refresh_token server-side with Okta?
Responded to your post here https://devforum.okta.com/t/getting-refresh-token-server-side-sessiontoken/12419/3.
Aside from making a call directly to /token with your access token you can also check our Early Access feature called Refresh Token Rotation. Let us know if this helps!
I was able to use the CODE flow and redirect from server-side to the authorized endpoint like so:
https://{YOUROKTADOMAIN}/oauth2/default/v1/authorize?client_id={YOURCLIENTID}&response_type=code&scope=openid%20offline_access&response_mode=query&redirect_uri={YOURSERVERSIDEGETURI}&state={Guid.NewGuid()}&sessionToken={SessionToken From Auth API}
This call will post back to my same server, so i can handle token myself and create my own cookie.

Authentication with ServiceStack and more provider

I state that I use ServiceStack to authenticate my services.
My problem is the following I am developing two authentication methods via credentials and via API key.
The implementation is correct but I would like some services to be authenticated through Credentials while other services through API key. Reading from documentation it seemed to me that I understood that it was enough to insert in the [Authenticate] attribute the provider parameter equal to the property Name of the reference Auth class (Credentials or API), getting [Authenticated ("apikey")] for example.
Unfortunately, implementing the example above, if I authenticate with credentials, I can call the service while I would only like this service to be called via API key.
Do you have any solutions?
thanks a lot
The [Authenticate(provider)] will check if the User is considered to be authenticated according to that Auth Provider where it calls the AuthProviders IsAuthorized() to verify if the session is authenticated.
If you want to mandate that a Request was authenticated using an API Key you can check for it in your Service implementation, e.g:
if (Request.GetSession().AuthProvider != ApiKeyAuthProvider.Name)
throw HttpError.Forbidden("Must authenticate with API Key");

JAX-RS Jersey servlet JJWT

I have a couple of days following a few issues but I can not find the solution .
I have followed these issues: Custom JAX-RS authorization - using JWT in each request and
Best practice for REST token-based authentication with JAX-RS and Jersey
but I do not understand how to use filters.
I need to create a token for a android app Use the resources of my web service.
I can not just create a token and send it ?
I 'm using jjwt https://github.com/jwtk/jjwt but I think it right, a piece of code:
#POST
#Produces("application/json")
#Consumes("application/x-www-form-urlencoded")
public Response authenticateUser(#FormParam("username") String username,
#FormParam("password") String password) {
try {
// Authenticate the user using the credentials provided
// authenticate(username, password);
// Issue a token for the user
String compactJws = Jwts.builder().setSubject(username).signWith(SignatureAlgorithm.HS512, "pepe").compact();
// Return the token on the response
return Response.ok(compactJws).build();
} catch (Exception e) {
return Response.status(Response.Status.UNAUTHORIZED).build();
}
}
If anyone can help me , thanks ...
Si alguno me puede responder en castellano, mejor.
PD: Sorry if I asked the question wrong, I'm new in stackover... and sorry for my English
I am the author of the answer about token-based authentication in JAX-RS. This authentication method can be summarized in the following steps:
Exchanging hard credentials for a token
No filters are required to do it. You should have an endpoint (a JAX-RS resource method) to perform the authentication using hard credentials (like username and password). If the credentials are valid, the endpoint is going to issue a token that will be sent to the client in the response payload. The client must sent this token in the Authorization header of each request.
The endpoint that issues the tokens must not be protected, that is, no authentication must the required to access it. Once you have an Android application as client, I think you will find better consuming application/json instead of application/x-www-form-urlencoded. My answer provides details on how to do it.
Validating the token
Here the authentication filter comes into play. When using filters to validate the tokens, you can keep your endpoints lean and business focused.
The idea behind the filter is to intercept the requests to protected resources, extract the token from the Authorization header and validate it. If the token is valid, the request will proceed to the requested endpoint. If the token is invalid, the request will be aborted.
Besides the authentication filter, you can have other filters to perform authorization, for example. In the authentication filter, you must check if the token is valid and then find the user you issued the token for. In the authorization filter, you must ensure the user has enough permissions to access the requested resource. Other filters can be created according to your needs.
The code you have provided is valid to a issue a new token for a web application (uses application/x-www-form-urlencoded), but for android application It would probably be more appropriate send credentials as a json POST or in a Authorization header
After this, the client application receives the token, stores it and needs to include the JWT in every request to server. You can include the token in headers or in a request param. The server must validate the token signature, and other fields like sub (the userId) and exp (expiration time).
Using a filter, like the AuthenticationFilter provided in the example, simplifies the authentication process. It can intercept all the requests and perform the validation in a unique point. If not, you would have to validate the JWT in each method of your bussiness logic
If you have doubts about how to configure the filters I suggest to post in SO an specific question

OAuth resource owner password flow and HMAC

I have a web api application which implements the Resource Owner Password flow from OAuth specification. Everything works correctly.
Actually I configure everything in my WebApiConfig class by using an Authentication filter like this
// Configure Web API to use only bearer token authentication.
config.SuppressDefaultHostAuthentication();
config.Filters.Add( new HostAuthenticationFilter( OAuthDefaults.AuthenticationType ) );
As some of my customer asked for a different method of authentication I am evaluating to add a couple of features to my services but stil did not have clear how those features can work together.
In particular I cam across a link which explain in very easy words how to implement a HMAC authentication in web api.
Can I implement this authentication method and let the client to choose which one he want to use? Do they can cohesist together?
Yes, your web api service can send back multiple schemes in the WWW-Authenticate challenge. In your case it can send back 'bearer' and 'hmac' for example.
See also this question for more info on using multiple schemes.
BTW, it's not your web api service that supports Resource Owner Password flow. The client uses this flow to get a token from the authorization server that it can use in a bearer scheme with your service (resource server). HTH.

open custom authentication module access http session

How can i access http session and request/response from openam custom authentication module? Any one has idea?
I am trying openam sample auth module, but no where i found a way to access httpservletrequest etc.
I have a requirement to access httpsession as i am working on challenge/signature authentication. I store the challenge in session on Login.jsp and client signs it. Now inside custom auth module, i need access to that challenge in session to verify.
Is it passed somewhere in init
public void init(Subject subject, Map sharedState, Map options)
Every custom auth module extends from AMLoginModule which has HttpServletReequest :)