ASP.NET 5 OAuth bearer token authentication

后端 未结 3 1988
有刺的猬
有刺的猬 2021-01-31 06:33

I’m trying to implement OAuth bearer token authentication in ASP.NET 5 and am struggling to find an example of how to do this because the OWIN stuff has changed in ASP.NET 5.

3条回答
  •  再見小時候
    2021-01-31 07:09

    The real kicker here is the token generation. I've managed to build one using the default Microsoft.AspNet.Security.OAuthBearer package, but it wasn't easy.

    // Injected from the constructor; this is why we configured the options above rather 
    // than simply passing them to the UseOAuthBearerAuthentication()
    private readonly OAuthBearerAuthenticationOptions bearerOptions;
    
    // In your /Token action...
    var handler = bearerOptions.SecurityTokenValidators.OfType()
        .First();
    // The identity here is the ClaimsIdentity you want to authenticate the user as.
    // You can get this using the SignInManager if you're using Identity.
    var securityToken = handler.CreateToken(
        issuer: bearerOptions.TokenValidationParameters.ValidIssuer, 
        audience: bearerOptions.TokenValidationParameters.ValidAudience, 
        subject: identity);
    var token = handler.WriteToken(securityToken);
    // The var token is your bearer token
    

    My full solution is detailed here: Token Based Authentication in ASP.Net 5 (vNext).

提交回复
热议问题