微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

了解ASP.NETMVC,Web API中的令牌生成/验证

如何解决了解ASP.NETMVC,Web API中的令牌生成/验证

我正在开发一个MVC项目,在该项目中,我正在生成令牌,以授权拥有此令牌的人说出著名的“ Hello World!”。 由于我是ASP.NET中的新手,因此我不了解WHERE和WHO会生成令牌,并且一旦生成令牌,令牌将保存在何处(或如何保存)。另外,我不知道在启动带有令牌的Get / Post后谁会验证令牌。 最终目的是尝试更改生成的令牌的类型,以获得像JWT令牌这样的新令牌,而不是基本令牌。 我正在使用OWIN。

这是我认为很重要的部分,

using Microsoft.Owin;
using Microsoft.Owin.Security.OAuth;
using Owin;
using ExampletoUnderstand.Models;
using ExampletoUnderstand.Providers;

public partial class Startup
{
    public void Configuration(IAppBuilder app)
    {
        ConfigureAuth(app);
        var config = new HttpConfiguration();
        WebApiConfig.Register(config);
        app.UseWebApi(config);
    }
}

/*Following the partial class Startup.Auth.cs*/
public partial class Startup
{
    public void ConfigureAuth(IAppBuilder app)
    {
        app.CreatePerOwinContext(ApplicationDbContext.Create);
        app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
        app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);
        var oAuthServerOptions = new OAuthAuthorizationServerOptions()
        {
            // AuthorizationCodeFormat = new JwtFormat(audienceId,new SymmetricKeyIssuerSecurityTokenProvider(issuer,signingKey)),// da togliere se non funziona
            AllowInsecureHttp = true,TokenEndpointPath = new PathString("/token"),AccesstokenExpireTimeSpan = TimeSpan.FromMinutes(3),Provider = new AuthorizationProvider ()
        };
        // Token Generation
        app.USEOAuthAuthorizationServer(oAuthServerOptions);
        app.USEOAuthBearerAuthentication(new OAuthBearerAuthenticationoptions());
    }
}

然后我按照一些指南开发了一个提供程序,结果是这样的:

using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.IdentityModel.Tokens;
using Microsoft.Owin.Security.OAuth;
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Threading.Tasks;
 
public class AuthorizationProvider : OAuthAuthorizationServerProvider
{
    public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
    {
        context.Validated();
    }
    public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {

        context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin",new[] { "*" });
        var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();
        IdentityUser user = await userManager.FindAsync(context.UserName,context.Password);
        if (user == null)
        {
            context.SetError("invalid_grant","The user name or password is incorrect.");
            return;
        }
        
        var identity = new ClaimsIdentity(context.Options.AuthenticationType);
        identity.AddClaim(new Claim(ClaimTypes.Name,context.UserName));
        identity.AddClaim(new Claim(ClaimTypes.Role,"User"));
        context.Validated(identity);
    /*WHO GENERATES THE TOKEN HERE?? WHICH IS THE ALGHORITHM USED??*/
    }
}

使用邮递员,我得到这样的结果。

{
  "access_token": "mxHZzefB6pAc6WnTkjeamyxgDMUVNy64CkmtTEwwN2yLZkDQkfDy3J6EIVVLDNRN1-XkeA50Xqk0oB9DEprEuCzGAdsgOG69iPUmf7i7OEZuJfnIXWf0S_qf23gsU5Ppr_lBnpP8pd1RRSQNwvFk_HiumdrJTm91cKenhvWEfbg8a9qhQCH4cwDCzbZ1mwR682WqApk0NOUK7w8UXR7kqIKrS9S2Y4azAvh-9zNWXB3lEkCtoZgDKgLBWotIc9cA8N5FVxd_WOYchA2BYBkgkisZtuW0CigJ4l5Om0zzJJypGGS22foyAdnHFbgkpcIW","token_type": "bearer","expires_in": 179
}

调用以下方法,我得到“ Hello World!”。

/*Method inside Homecontroller.cs that extends a controller*/
[Route("/api/HelloWorld")]
[HttpGet]
[Authorize] // How does the authorization works? 
public string HelloWorld()
{
    return "Hello World";
}

非常好,但是我想知道它是如何工作的。 如果有人有建议,文本,有效的书籍/指南资料或其他内容,我将不胜感激!

预先感谢

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。