Authorize a web api page

osyris 236 Reputation points
2021-07-06T16:39:21.627+00:00

I have looked in the React authentication template in visual studio
But i could not find anything about redirecting to a login or register page if a user is not authorized

when I [Authorize] a Route the only thing that happens is that it wont fetch data
so i get a "Unexpected token < in JSON at position 0"

it hides some information but it is not really what, I want the entire page to redirect to a special route like the login or register page

is this done in the back-end with (asp net core) or should it be done by the front-end (reactjs)

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,188 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Michael Taylor 48,576 Reputation points
    2021-07-06T18:11:05.72+00:00

    You'll need to enforce authentication on client and server. If you're building a React app you're likely doing SPA. Since SPA doesn't route via server you'll need to add logic for "authentication" on the client side routes. How you do that in React I don't know as I don't use that framework.

    On the server side the Authorize attribute on controllers/actions will trigger a challenge if not authenticated. To configure that it depends on the version of the framework you're using. To be honest this is fully documented online so repeating it here isn't that useful. Just read the docs. It is also going to be dependent upon what you're using to authenticate (AD, OpenID, etc).

    The easiest way to get the server side code is to create a new ASP.NET Core app using the same template and version that your actual app is using. As part of the creation it has an option to use authentication. Select that option and to use individual accounts. It'll auto-generate the necessary code. That code will reside in startup.cs. Within the Startup class are the 2 Configure methods. The Configure method sets up the middleware and adds authentication/authorization via UseAuthentication and UseAuthorization. IIRC these don't have to be modified and can be dropped into your actual app.

    The ConfigureServices method is what configures things and will also have a call to configure the authentication. It is here that you'll specify what authentication you use (OpenID, AD, etc) and configure the provider. It is within the (authentication type-specific) options passed to the configuration method where you'll specify things like redirect URL, cookie names, etc. Refer to the docs for the provider you're using as to what all the options mean. OpenID is pretty consistent but other providers probably use different terminology.

    0 comments No comments