Owin Bearer Token Authentication + Authorize controller

后端 未结 4 1513
深忆病人
深忆病人 2020-12-24 13:40

I\'m trying to do authentication with Bearer tokens and owin.

I can issue the token fine using the grant type password and overriding GrantResour

4条回答
  •  醉梦人生
    2020-12-24 14:27

    I was looking for the same solution, I spent a week or so on this and I left it. Today I started to search again, I found your questions and I was hoping to find an answer.

    So I spent the whole day doing nothing other than trying all the possible solutions, merging suggestions with each other, I found some solution but they were long workarounds, to make the long story short here is what I found.

    First of all if you need to authenticate the Web site with a custom third party identity provider token you need to have them both using the same machineKey or you need to have them both on the same server.

    You need to add the machineKey to the system.web section as following:

    Web.Config

    
        
        
        
        
    
    

    Here is a link to generate a new machineKey :

    Now you need to move to the Startup.Auth.cs file where you can find the Startup.cs partial class, you need to define the OAuthBearerOptions

    Startup.Auth.cs

    public partial class Startup
    {
        public static OAuthBearerAuthenticationOptions OAuthBearerOptions { get; private set; }
        ...
    
        public void ConfigureAuth(IAppBuilder app)
        {
            // Configure the db context, user manager and signin manager to use a single instance per    request
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext(ApplicationUserManager.Create);
    
            OAuthBearerOptions = new OAuthBearerAuthenticationOptions();
            app.UseOAuthBearerAuthentication(OAuthBearerOptions);
            ...
        }
    }
    

    Replace your Login action inside AccountController with the following:

    AccountController.cs

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task Login(LoginViewModel model, string returnUrl)
    {
        /*This will depend totally on how you will get access to the identity provider and get your token, this is just a sample of how it would be done*/
        /*Get Access Token Start*/
        HttpClient httpClient = new HttpClient();
        httpClient.BaseAddress = new Uri("https://youridentityproviderbaseurl");
        var postData = new List>();
        postData.Add(new KeyValuePair("UserName", model.Email));
        postData.Add(new KeyValuePair("Password", model.Password));
        HttpContent content = new FormUrlEncodedContent(postData);
    
    
        HttpResponseMessage response = await httpClient.PostAsync("yourloginapi", content);
        response.EnsureSuccessStatusCode();
        string AccessToken = Newtonsoft.Json.JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync());
        /*Get Access Token End*/
    
        If(!string.IsNullOrEmpty(AccessToken))
        {
                var ticket = Startup.OAuthBearerOptions.AccessTokenFormat.Unprotect(AccessToken);
                var id = new ClaimsIdentity(ticket.Identity.Claims, DefaultAuthenticationTypes.ApplicationCookie);
                AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = true }, id);
    
                return RedirectToLocal(returnUrl);
    
       }
    
       ModelState.AddModelError("Error", "Invalid Authentication");
       return View();
    }
    

    The last thing you need to do is to place this line of code in the Global.asax.cs to avoid Anti Forgery exceptions:

    Global.asax.cs

    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier;
    
            …
        }
    }
    

    Hope this would work for you.

提交回复
热议问题