Can I use both of Basic and Bearer in Authorization header? - http

I implemented JWT token for API Authorization. Every request that required authorization is sent with JWT token in Authorization header like this: Authorization: Bearer <token>.
Everything is clear for me about JWT token except login request.
I just want to use Authorization: Basic <credentials> where login request. I suppose sending username and password as plain text seems not good. But I'm not sure.
Is it okay to use Basic <credentials> on login request and then use Bearer <token> on other request?

Good morning. It is best practice to create a method and invoke that using POST call. Pass the Login Credentials as an object to the post method. The login method should return the JWT token. Once you receive the JWT token, then onwards please use bearer XXXXXXXX.
Example:
[AllowAnonymous]
[HttpPost]
public IActionResult CreateToken([FromBody]LoginModel login)
{
// Your logic to Authenticate and Generate the JWT TOKEN.
return response;
}

Related

JWT Authentication and authorization without using api controller

I am trying to make login with JWT authentication. But wherever i find the way of use it always use with api but I do not want to use api i just want to creat just separate controller for login.Kindly tell me how to authorize with jwt and without api.
According to your description,if you want to enable the JWT authentication for MVC, I suggest you could follow this article.
The difference between the JWT authentication for the MVC and Web API is you need store the token at somewhere, since the web api you need to set the token inside the Authorization header for each request.
To solve this issue, you could follow the article which I shared, it store the token inside the session and then it will write a middleware which will read the token from session and then set it at the request header.
The middleware like this.
app.Use(async (context, next) =>
{
var token = context.Session.GetString("Token");
if (!string.IsNullOrEmpty(token))
{
context.Request.Headers.Add("Authorization", "Bearer " + token);
}
await next();
});
For store the token, you could write you own codes and then using the session storage to store the token.
HttpContext.Session.SetString("Token", generatedToken);

How is this access token stored on the client, in FastAPI's tutorial "Simple OAuth2 with Password and Bearer"

I'm pretty new to FastAPI and OAuth2 in general. I just worked through the tutorial "Simple OAuth2 with Password and Bearer" and it mostly made sense, but there was one step that felt like magic to me..
How does the access token get stored onto the client and subsequently get passed into the client's requests?
My understanding of the flow is that it's basically
User authenticates with their username and password (these get POST'ed to the /token endpoint).
User's credentials are validated, and the /token endpoint returns the access token (johndoe) inside some JSON. (This is how the user receives his access token)
???
User make a subsequent request to a private endpoint, like GET /users/me. The user's request includes the header Authorization: Bearer johndoe. (I don't think the docs mention this, but it's what I've gathered from inspecting the request in Chrome Developer Tools)
The authorization token is then used to lookup the user who made the request in (4)
Step (3) is the part that I don't understand. How does the access token seemingly get stored on the client, and then passed as a header into the next request?
Demo
When you run the code in the tutorial, you get the following swagger docs. (Note the Authorize button.)
I click Authorize and enter my credentials. (username: johndoe, password: secret)
And now I can access the /users/me endpoint.
Notice how the header Authorization: Bearer johndoe was automagically included in my request.
Last notes:
I've checked my cookies, session storage, and local storage and all are empty
The authorization header disappears if I refresh the page or open a new tab
I suspect Swagger is doing something under the hood here, but I can't put my finger on it.
If you need persistence for the token you'd usually use localStorage or similar, but in SwaggerUIs specific case, the authentication information is kept internally in the library.
If you have enabled persistence SwaggerUI will persistent the access token to localStorage:
export const persistAuthorizationIfNeeded = () => ( { authSelectors, getConfigs } ) => {
const configs = getConfigs()
if (configs.persistAuthorization)
{
const authorized = authSelectors.authorized()
localStorage.setItem("authorized", JSON.stringify(authorized.toJS()))
}
}

What is the OpenID Connect access token for?

The OpenID Connect JWT token contains both an id_token and an access_token (Like "access_token": "SlAV32hkKG"). What is the access_token for?
ANSWER EXAMPLE
Just adding an example to complement the answers taken from this linked article
User Info Endpoint Request
GET /userinfo HTTP/1.1
Host: openid.c2id.com
Authorization: Bearer SlAV32hkKG
User Info Endpoint Response
HTTP/1.1 200 OK
Content-Type: application/json
{
"sub" : "alice",
"email" : "alice#wonderland.net",
"email_verified" : true,
"name" : "Alice Adams",
"picture" : "https://c2id.com/users/alice.jpg"
}
The answer to your question lies in the section 5.3 and 16.4 of the specification. The access token is used to access the userinfo endpoint which is a protected resource.
16.4. Access Token Disclosure
Access Tokens are credentials used to access Protected Resources, as defined in Section 1.4 of OAuth 2.0 [RFC6749]. Access Tokens represent an End-User's authorization and MUST NOT be exposed to unauthorized parties.
[...]
5.3. UserInfo Endpoint
The UserInfo Endpoint is an OAuth 2.0 Protected Resource that returns Claims about the authenticated End-User. To obtain the requested Claims about the End-User, the Client makes a request to the UserInfo Endpoint using an Access Token obtained through OpenID Connect Authentication. These Claims are normally represented by a JSON object that contains a collection of name and value pairs for the Claims.
tl;dr - Access token grants authorization to access a protected resource where the ID token is consumed by the client for authentication.
Access token
Being an extention to OAuth2.0, OpenID Connect keep tokens/prameters defined in OAuth2.0 specification. Access token is one such thing. As defined by the protocol, access token is used to access protected resources. It replaces user credentials, manually generated tokens or security keys which were used in good old days (ex:- Think about basic authentication).
Note the access token could be an opaque string. Which means it's nothing that could be consumed by the client which recieves it. But the authorization server knows what it is. For example, introspection endpoint (RFC7662) can be used to validate the validity of an access token. And access token can be a JWT too depending on the usage and implementation.
ID token
This is what OpenID Connect introduced to OAuth2.0. ID token is a JWT and it is consumed by client to authenticate the end user(the resource owner). By validating an ID token, client have the ability to authenticate. Due to this fact, one can argue it surves one time usage.
Also note that in some implementations, ID tokens are being used as bearer tokens. That mean, ID token used like an access token for authentication and authorization.

Call /oauth/token endpoint from method

Is it possible to call /oauth/token endpoint from method to receive access_token / refresh_token?
I need to accept username and password inside the controller and then get the access_token from oauth2 endpoint. What class is responsible for it?

How does Identity.GetUserId() finds the user Id?

Question
How does User.Identity.GetUserId() finds the current user's Id?
Does it find the user Id from the Cookies, or does it query the database? Or any other methods?
Problem
For some reason, User.Identity.GetUserId() returns null when I add a valid Bearer Token to my Http request header and send the request to my controller's endpoint:
// MVC Controller Action Method
[Authorize]
public HttpResponseMessage(UserInfoViewModel model)
{
// Request passes the Authorization filter since a valid oauth token
// is attached to the request header.
string userId = User.Identity.GetUserId();
// However, userId is null!
// Other stuff...
}
How does User.Identity.GetUserId() finds the current user's Id?
ClaimTypes.NameIdentifier is the claim used by the function User.Identity.GetUserId()
You would need to add the claim in your authorization code,
identity.AddClaim(ClaimTypes.NameIdentifier, user.Id);
identity is of type ClaimIdentity.
When the user is logged into your app, the server, using ASP.NET Identity, validates your user using DB and creates a valid token that returns to the UI. This token will be valid to its expiration and has inside all information needed to authenticate and authorize the user, including the user's Id. Next calls from client side to server side must be done using this token in the http request header, but server will not call the DB again, because ASP.NET identity knows how to decrypt the token and get all the information of your user.
The use of cookies is only a way to store the token in the client side. As I commented above, you have to send the token on the next requests after the login, so you can store this token in cookies or in Session Storage in your browser.
First, make sure you're not allowing for non-authenticated users.
After that, you want to parse Bearer tokens you have to configure it.
You're going to the need this package Microsoft.Owin.Security.OAuth
And at startup if have to configure ASP.NET Identity to use Bearer Authentication with:
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions {
// your options;
});
Probably on your StartupAuth.cs file

Resources