Understanding the VS2013 MVC5 SPA Template WebAPI Security Features - asp.net-web-api

I am trying to understand the security features of the VS2013 MVC5 SPA Template WebAPI.
In Startup.Auth.cs there is this -
TokenEndpointPath = new PathString("/Token")
and this -
AuthorizeEndpointPath = new PathString("/Account/Authorize")
In my understanding, the AuthorizeEndPointPath is for when your acting as a 3rd Party OAuth authorization server.
However how it is used in the template, the flow seems to be
Login via Forms Authentication
Redirect to a secure page
Javascript checks for a bearer token in the local storage, it doesn't exist, so it redirects to this Authorize endpoint.
window.location = "/Account/Authorize?client_id=web&response_type=token&state=" + encodeURIComponent(window.location.hash);
Logs into app with OAuth security, returns token, which will be passed on subsequent API requests.
The /Token endpoint never seems to be used. A prior version of this templated did an ajax post to /Token to login. I have a similar situation where the website is secured via Forms authentication/cookies but the WebApi is secured by Bearer token.
Is the Authorize endpoint being used correctly in this SPA template - is this the correct pattern to follow? It seems like the appropriate way to authenticate for bearer token security "internally" for the app would be a "client credentials grant" though not sure how to generate the "secret".

Related

wsfed authentication in webapp-webapi

The issue I am facing is to get webApi authenticated with bearer token received from webapp authentication.
Created web app, Angular template of .net core 2.1. Aded WsFed authentication to it. https://demoapp (dummy name)
Created Web Api app. Added wsfed authentication to it. https://demoapp-api (dummy name)
Now target is to authenticate web app, use token from there to make calls to api, and get data.
In WebApp, in OnTicketReceived WsFederationEvent, acquiring token using AcquireTokenAsync(AppId, credential);
Doing this because, we receive SAML token from WsFed.
Here tried with AppId of WebAPI, and also of WebApp. Both tokens do not work.
Passing this token as Bearer token in header to API.
When hitting API, facing redirection for authentication.
Ideally, when sending token, it should be allowed, right ?
I have added permissions of WebAPI on WebAPP in Azure portal, and also vice-versa.
Acquiring token using AppSecret.
Am I missing something here ? Or I am trying to achieve something which is not possible with WsFed ?
Can anyone please help with this webapp-webapi-wsfed scenario ?

Django rest framework working with multiple apps

My aim is to authorize browsable API(first app) using the JWT token generated(second app).
I have two apps created,
1. API - has all the data
2. Authentication - generate JWT tokens after validating the user.
Now, when I try to access the API after generating the token it says,
Authentication credentials were not provided.
Trying to access the API (passing the bearer whatevertoken)
I mean, is there a way to authenticate the Browsable API using JWT token? Instead of creating a user session.
Passing Authorization header as,
"Authorization: JWT token"
authenticates the user.
But, limits me to browse the API in a browser. Is there any way we can implement Browsable API using JWT authentication?
UPDATE
A thorough reading on
Authentication classes
Permission classes
Django settings
Helped in understanding the core concepts and apply appropriate solutions.

Return JWT token to javascript SPA from oauth login

I'm developing a javascript spa in vue.js which is going to eventually be a cordova application. As well as a backend api built with lumen.
I'm trying to provide login with facebook and google functionality. I've added the laravel socialite package and created a redirect and callback route. Ive created a page in my spa with the login buttons that direct to my api redirect. The user is redirected to facebook's oauth mechanism I login, the callback routes handle function looks something like this
public function handleProviderCallback($provider)
{
$oauthUser = $this->socialiteManager->with($provider)->stateless()->user();
$userEntity = $this->repository->findOrCreateOauthUser($oauthUser);
$providerEntity = app()
->make('em')
->getRepository('Entities\Social\Provider')
->findOneBy(['name' => $provider]);
if(is_null($providerEntity))
{
throw new \Exception('Oauth Provider not found');
}
$socialAccountEntity = app()
->make('em')
->getRepository('Entities\Social\SocialAccount')
->findOrCreateSocialAccount($providerEntity, $oauthUser, $userEntity);
$token = $this->auth->fromUser($userEntity);
$resource = $this->item($token)
->transformWith($this->transformer)
->serializeWith(new ArraySerialization())
->toArray();
return $this->showResponse($resource);
}
It basically gets a the oauth user, finds or stores them in the database, finds or stores their social account info,
$token = $this->auth->fromUser($userEntity);
Then authenticates them with JWT issuing a token. Which is then serialised and returned as a json response.
The problem is that the response is given while on the backend application, im never returned back to the javascript SPA.
Instead of returning json I could do some redirect like
return redirect()->to('/some-spa-callback-route');
But should the api be aware of the SPA location? and how will this work when the SPA is ported into cordova, as the mobile application wont have a url?
My thoughts are that A
The social provider should redirect directly to the SPA at which point it should make another request exchanging the authorisation code for a JWT token.
B it redirects to the SPA with a query string containing the token, which doesn't sound secure.
or c sends some type of cookie back.
And I am still confused as to how to actually redirect from my api to a mobile application.
In the end I ended up with the following login flow
User is directed to Oauth provider
Oauth provider returns an access token to the client
the client sends the access token to my api
my api sends a renew request to the Oauth provider
the Oauth provider validates the token and returns a new one to my api
my api exchanges the access token for a jwt token
my api returns the jwt token to the client
In my opinion it is the only correct way to authenticate SPA applications, and it is important to renew the Oauth token the client provides rather than blindly exchanging for a jwt as you can't trust the client, and is better than issuing redirects from the api that isn't very restfull
Instead of dealing with 2 services, your spa should talk to a single auth service in your backend. You register your service as the oauth callback and you handle oauth/jwt as you described. Your auth service can also be the decision point for user (re-)authentication. Since your frontend calls your backend directly, you can now return the json payload back to your web/mobile caller.

Authenticate MVC clients with Web API Tokens

Currently I have created a WebAPI Project using identity framework and I have setup tokens to be returned when authenticating with the API.
So now I am looking at creating a standalone MVC application that will allow the user to make calls to the WebAPI to get back end data.
The goal is to separate functionality so that other applications can also start interacting with back end data through web calls.
So the confusion now is how do I setup my MVC project so that I can use the Authorize attributes on controllers with the token received from the WebAPI. I think I need to enable bearer tokens in the ConfigureAuth method in Startup.Auth.cs. However will that be sufficient enough? Or do I also need to enable the cookie authentication?
MVC and Web Api are fundamentally different when it comes to authentication. With Web Api, the bearer token has to be set in the header of the request, but this is not an issue as all API requests are done programmatically by the client, i.e. there's human-intervention involved in setting up the client to authenticate the request properly.
MVC is a different beast in that the actions are accessed generally via a web browser, which will not automatically affix a bearer token to the request header. What it will do is pass cookies set by the server back to the server. That's why cookie auth is used most typically for MVC web applications.
What you should do is enable cookie auth for the MVC site and then set up your sign in action to authenticate via the Web Api. When you get back a valid auth from the Web Api, then you can manually sign in the user via the Identity API:
await SignInManager.SignInAsync(user);

Authorize using Oauth2 Token in Asp.Net WebAPI

Hello I am building an ASP.Net WebApi. First I authorized the WebApi using basic authentication .net membership provider and the Thinktecture Identitymodel.
var authConfig = new AuthenticationConfiguration();
authConfig.AddBasicAuthentication((username, password) => Membership.ValidateUser(username, password));
config.MessageHandlers.Add(new AuthenticationHandler(authConfig));
I guess it couldn't be made any easier.
To take it a step further i've set up the Thinktecture IdentityServer which provides me with oauth2 tokens. My question is how do i validate the access tokens the client sends me (the WebApi) with the identity server?
I've been looking into the AddJsonWebToken methods the IdentityModel provides, but I can't really figure out wich uri (endpoint) in the identityserver i should call to validate the token. Probaply I'm just completly lost here and missing the point, any help would be greatly appriciated!
To summarize:
How do I validate the access_tokens i receive in my WebApi and how do I wire that to the [Authorize] attribute?
Simply call AddJsonWebToken in you web api config - and add the issuer name, signing key and realm uri.
There is no need to call idsrv for validation.
Here's a sample:
http://leastprivilege.com/2012/05/26/thinktecture-identitymodel-and-asp-net-web-api/

Resources