未经授权使用代码验证Owin生成的令牌

时间:2020-03-27 10:44:51

标签: c# asp.net-web-api

我正在使用Microsoft.Owin代码生成令牌。验证后,用户可以使用用户名和密码获取令牌。我想在请求用户中传递相同的令牌在json请求中。我不想使用 [授权] 。有没有机会获得生成的令牌。下面是我的代码。

public void ConfigureOAuth(IAppBuilder app)
        {
            OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
            {
                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString("/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(7),
                Provider = new CustomAuthorizationServerProvider()
            };

            // Token Generation
            app.UseOAuthAuthorizationServer(OAuthServerOptions);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());    
        }

public class CustomAuthorizationServerProvider : 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[] { "*" });

        AuthRepository authRepository = new AuthRepository();
        bool isValid = authRepository.ValidateUser(context.UserName, context.Password);

        if (!isValid)
        {
            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"));
        //var ticket = new AuthenticationTicket(identity, new AuthenticationProperties());
        //context.Validated(ticket);

        context.Validated(identity);
    }

0 个答案:

没有答案