Azure B2C Implicit Flow not working in ASP.NET when "Access Token" is disabled on the app registration - asp.net-mvc-4

I'm testing authentication for a server based web app.
I think the best way to login the browser is with Implicit Flow to obtain only an id_token via an HTTP POST.
I've configured my OpenIdConnectAuthentiationOptions like:
Scope = OpenIdConnectScope.OpenIdProfile,
ResponseType = OpenIdConnectResponseType.IdToken,
ResponseMode = OpenIdConnectResponseMode.FormPost,
These should be the options to do what I am asking.
When I try to authenticate, I am given the error:
'AADB2C90057: The provided application is not configured to allow the
'OAuth' Implicit flow.
But, I have enabled Implicit Flows in the app registration in Azure AD B2C. However, I specifically am NOT enabling "Access Token," because obviously I am NOT requesting one.
I'm specifically following the instructions to select only "ID tokens," for web apps using hybrid authentication.
If I change the option to ResponseType = OpenIdConnectResponseType.CodeIdToken I have the same issues. Although, I think this response type also requests an Access Code.
If I enable both ID Tokens and Access Tokens, then the app logs in fine. Why do I have to enable "Access Tokens" when I am only requesting an ID Token?
The basis for what I am attempting is described here: https://learn.microsoft.com/en-us/azure/active-directory/develop/tutorial-v2-asp-webapp

Please check the Important note from OAuth 2.0 implicit grant flow | Microsoft Docs which is the same doc which can be obtained by clicking 'learn more about tokens.' hyperlink.
NOTE:
Which says we need to check both idtoken and accesstoken to obtain id token or access token or in combination of both, but the response depends on the responseType mentioned in the authentication request (you may read same document further for the details).
i.e.;
You will receive idtoken , if you have given responsetype =id_token
You will receive accesstoken if responseType=token
You will receive code and id token in case of responsetype is
id_token+code
Request an ID token as well or hybrid flow

Related

Unable to execute silent refresh after receiving id_token ,while implementing implicit flow , both azure ad and google identity services

I've enabled implicit flow support in azure AD registration which says:-
"To enable the implicit grant flow, select the tokens you would like to be issued by the authorization endpoint:"
And i am trying to authenticate for multiple identity provides hence not using msal or adal.
But am unable to achieve silent refresh using hidden iframe.
Sent a authorization request with scope including openid and response type as id_token(in a popup)
Receive id_token , and everything else including session state.
Now (via Iframe) I am trying to fetch token using silent auth by sending the propmt=none,
and id_token_hint = prev_id_token have also tried sending login_hint = preferred_username (which i got from JWTtoken.payloadObj.preferred_username)
P.S have also tried sending response_type as both id_token and token initially, and then try an silent refresh, its failing with this error everytime:-
error=login_required&error_description=AADSTS50058%3a+Session+information+is+not+sufficient+for+single-sign-on.%0d%0aTrace+ID%3a+5ceb4386-f4b1-40aa-8fb5-797c14379b00%0d%0aCorrelation+ID%3a+3401101e-9098-4048-bb05-78926181d733%0d%0aTimestamp%3a+2019-04-17+10%3a12%3a47Z&state={my state}
Please let me know what i am missing , it needs to be implicit flow.
and i need to achieve a silent refresh using hidden i frame.
I've implemented it as it is mentioned in this post:-
https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-implicit-grant-flow
am unable to do the highlighted part in this image

IdentityServer4 with LDAP/AD authentication without UI

I'm currently working on a project where I'm trying to set up a service based on IdentityServer4 (https://github.com/IdentityServer/IdentityServer4) that authenticates users by querying a local Active Directory via LDAP.
To achieve that, I also included the IdentityServer4.LdapExtension (https://github.com/Nordes/IdentityServer4.LdapExtension) in my project. The working example from the repository works fine (https://github.com/Nordes/IdentityServer4.LdapExtension/tree/master/Sample/IdentityServer) - but the custom logic is part of the UI, and I need my service to operate without any UI.
Simply adding
.AddLdapUsers<ActiveDirectoryAppUser>(Conf.GetSection("ldap"), UserStore.InMemory)
as described in the documentation does not change the request pipeline, as the provided login/validation methods are never executed - they are only triggered with calls from the UI (AccountController). However, as I said, I don't want to integrate any UI in this service and rather use the interface which the Token-Endpoint already provides (POST request with client_id and client_secret, response with JWT).
Is there a way to integrate LDAP authentication without rewriting big parts that work out-of-the-box as desired?
From your question it sounds like you already have a username and password. Note client_id != username and client_secret != password. client_id is the identity for a client application.
The grant type you are trying to use is called Resource Owner Password when using the authorize endpoint or password when using the token endpoint.
This grant type is used to support legacy systems and is not recommended for new development.
The code that you want to executed to authenticate a user is in LdapUserResourceOwnerPasswordValidator.cs and it should be executed if you pass the correct parameters to the token endpoint:
POST /connect/token
client_id=yourclientid&
client_secret=yourclientsecret&
grant_type=password&
username=yourusername&password=yourusernamespassword
See token endpoint documentation: https://identityserver4.readthedocs.io/en/release/endpoints/token.html
You can use Identity Model to help you make the token request:
var response = await client.RequestPasswordTokenAsync(new PasswordTokenRequest
{
Address = "https://demo.identityserver.io/connect/token",
ClientId = "yourclientid",
ClientSecret = "yourclientsecret",
UserName = "yourusername",
Password = "yourusernamespassword"
});
This is documented here https://identitymodel.readthedocs.io/en/latest/client/token.html

Okta: Failed to get authorization code through API call

I'm integrating Okta to my own IdP server by using Okta's API.
I'm implementing the Authorization code flow by following the steps below:
In my own server, use the /api/v1/authn endpoint to get the sessionToken.
Use the sessionToken to obtain the authorization by calling this endpoint: /oauth2/v1/authorize?client_id=" + clientId + "&sessionToken=" + sessionToken + "&response_type=code&response_mode=query&scope=openid&redirect_uri=" + redirectUrl + "&state=evanyang&nonce="
It's supposed to return a response with status code 302 and with the Location header containing the redirect url as well as the code value.
However, I keep getting a response with status code 200 and without the Location header, with a html body saying "You are using an unsupported browser." and "Javascript is disabled on your browser."
According to the API documentation: http://developer.okta.com/docs/api/resources/oidc.html#authentication-request, the sessionToken parameter is sufficient to do this: An Okta one-time sessionToken. This allows an API-based user login flow (rather than Okta login UI).
Am I missing any extra requirement for getting the authorization code through API? Please help.
Thanks in Advance :)
The Authorization Code grant type and the Authorization endpoint in there are meant to be access through a browser, not a non-browser client.
This issue is caused by obtaining session id between obtaining session token and authorization code. Once the session token is used to get session id, it becomes invalid, which means it cannot be used to get authorization code anymore.
According to Okta, the Authorization Code grant type and the Authorization endpoint and be used through a API-based web app too, as long as the session token is provided in the request: http://developer.okta.com/docs/api/resources/oidc.html#authentication-request. In fact, one can use this script(https://github.com/SohaibAjmal/Okta-OpenId-Scripts) to finish the flow.

django rest framework - token authentication logout

I have implemented the Token Authentication according to the django rest framework Docs.
Form what I read, the Token Authentication of DRF is quite simple - one token per user, the token doesn't expire and is valid for use always (am I right?).
I understand that there are better practices out there, but for now the DRF token authentication is fine for me.
my question is- what is the best practice for logout with the normal DRF token authentication?
I mean, when the user logs out, should I delete the token from the client side? and then on login get the token again? should I delete the token and generate a new one?
Anyone with experience with this?
Here's a simple view that I'm using to log out:
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
class Logout(APIView):
def get(self, request, format=None):
# simply delete the token to force a login
request.user.auth_token.delete()
return Response(status=status.HTTP_200_OK)
Then add it to your urls.py:
urlpatterns = [
...
url(r'^logout/', Logout.as_view()),
]
WHOLE IDEA OF TOKEN AUTHENTICATION:
Normally in authentication services, there is a lifetime associated with a token. After a specific time, the token will get expired. Here, we get an access token which has an expiry time sent along with it by the server. Now the client needs to send this token everytime in the request header so that the server can identify who the user is. Either we can keep track of when it expires or we can just keep using it until we get an INVALID_TOKEN error. In that case we would have to again get the token from the server.
The lifetime of the access_token is independent of the login session of a user who grants access to a client. OAuth2,lets say, has no concept of a user login or logout, or a session. The token is just used to identify the user if he is who he says he is.
The token is unique for a user and client. You may save it to cookies to enable something like remember me but on the server you don't need to delete it. Whenever the token expires, the client need to send a request to the server to obtain the token again.
Token Expiry in DRF Token Authetication:
Currently, DRF Token authentication does not support this functionality. You would have to implement it yourself or use a third party package which provides this functionality. It should check for token expiry and raise an exception if the token has expired.
To implement it yourself, you can subclass from the DRF Token Authentication class and add your logic.
You can even use a third-party package django-rest-framework-expiring-tokens.
Some References:
1. Token Authentication for RESTful API: should the token be periodically changed?
2. How to Logout of an Application Where I Used OAuth2 To Login With Google?
It sounds like SessionAuthentication is what you are really looking. You can start(login) a session via BasicAuthentication or TokenAuthentication. Then use sessionid as your "token" for the rest of api calls. The "token" expires when you logout or exceed certain timing.
If you run into csrftoken issue using session authentication, this could be a very helpful.

ASP.NET MVC DotNetOpenAuth authorization server how-to

I have this scenario: a corporate site (MVC 4) and a web shop; add OAuth 2 SSO functionality. Both sites have their own members, but the corp site (for which I'm responsible) must also work as an OAuth 2 authorization server and will store a web shop user id for each member. The shop requested the following endpoints:
Auth endpoint
• authorization:
…/oauth2/authorize?client_id={CLIENT_ID}&state={STATE}&response_type=code&redirect_uri={REDIRECT_URI}
• token
…/oauth2/token?code={TOKEN}&client_id={CLIENT_ID}&client_secret={CLIENT_SECRET}&redirect_uri={REDIRECT_URI}&grant_type=authorization_code
…/oauth2/token?refresh_token={TOKEN}&client_id={CLIENT_ID}&client_secret={CLIENT_SECRET}&redirect_uri={REDIRECT_URI}&grant_type=refresh_token
API endpoint
• getid (will return JSON with the shop id of the member):
…/oauth2/api/getid?access_token={TOKEN}
I don't have experience with OAuth, so I was looking at the DotNetOpenAuth samples and have concluded that I need to implement an OAuthAuthorizationServer, but modifying the sample to fit my requirements is difficult as it seems to do more and is complex.
As researching DotNetOpenAuth seems to be so time consuming, I'd like to ask: is modifying the OAuthAuthorizationServer sample the right approach? Or should I try to make a native implementation or try a different OAuth library that may be easier to use in my situation?
Please comment on my overall plan:
-keep the corp site member login flow standard forms auth, straightforward LogOn controller
-add an OAuth controller that will implement the three required endpoints as actions
-when the authorization action is reached, I validate the client and redirect to LogOn passing on the redirect_uri; I think the Authorize ActionResult from OAuthController.cs from the sample is where I should start investigating this, and return an AccountAuthorizeModel. Is this correct?
-after the user logs in, and if the login page was reached from the authorization endpoint, I redirect to redirect_uri with the code attached; I don't know where to start with this one. PrepareApproveAuthorizationRequest then PrepareResponse? Where does the code come from? Where in the flow should I add a new ClientAuthorization in the database?
-the shop will then use the code to get or refresh the token, from the /token endpoint; simply return HandleTokenRequest?
-with the token the shop site will be able to get the member data JSON; have to find out how to validate the token
Now, besides adding a Clients table to store the client ids and secrets, and ClientAuthorization to keep track of who's authorized, I don't know if the other tables from the DotNetOpenAuth sample are used and when: Nonce, SymmetricCryptoKey, User.
Modifying OAuth2AuthorizationServer.cs seems straightforward, I only have to add real certificates and make sure the clients are pulled from my data context.
Thanks!
I think you are right in most of the points. Let's comment them:
OAuth server should have 2 endpoints (not 3), as requesting token and refreshing token goes to the same endpoint (TokenEndpoint).
It depends if your are going to implement a different authentication server (or controller), or you are going to implement the authentication responsibility inside the authorization server. In case they are separated, the authentication server should be the one responsible of displaying the logon, authenticate and communicate with authorization server using OpenID protocol (Also supported by DotNetOpenAuth).
Once the user is authenticated, the authorization server should store the data of the user identity somehow, and return the authorization code (if using this Oauth flow) using DotNetOpenAuth functions:
var response =
this.AuthServer.PrepareApproveAuthorizationRequest(AuthorizationRequest,
User.Identity.Name);
return this.AuthServer.Channel.PrepareResponse(response);
finalResponse.AsActionResult();
I don't think you need to save nothing about the authorization process in the database, and the code is generated by DotNetOpenAuth and sent to the client into the query string of the redirection.
Then, the client should get the code (ProcessUserAuthorization) and call the TokenEndpoint. This endpoint is just returning HandleTokenRequest, that internally is calling to some OAuthAuthorizationServer functions, such as CreateAccessToken.
Once the client has the access token, it should call the resources, sending the token into the HTTP Header 'Authorization'. The resource server is the responsible to validate the token.
var resourceServer = new ResourceServer(new
StandardAccessTokenAnalyzer(signing, encrypting));
AccessToken token = resourceServer.GetAccessToken(request, scopes);
A store provider for nonce and crytoKeys is needed using this flow. Have a look to class InMemoryCryptoKeyStore in:
https://github.com/DotNetOpenAuth/DotNetOpenAuth/wiki/Security-scenarios
Hope this helps!