不为GET方法设置承载声明标识,但为POST方法设置标识

时间:2018-04-23 12:35:40

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

我正在使用ASP.net Web API 2(.net 4.7)。

我正在尝试在控制器中获取GET请求的承载声明身份(当前用户),但唯一的身份是Windows身份而不是承载声明身份。当我发出POST请求时,会提供持有者声明身份。

为什么会发生这种情况,是否有任何方法可以为GET请求设置不记名身份声明?我需要设置的启动(类)OAuth选项中是否有设置?

注意:“RequestContext.Principal”和“User.Identity”都会出现相同的结果

Startup.Auth.cs

public partial class Startup
{
    public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; }

    static Startup()
    {
        IClientService clientService = /* Newing up service */
        OAuthOptions = new OAuthAuthorizationServerOptions
        {
            TokenEndpointPath = new PathString("/token"),
            Provider = new OAuthAppProvider(clientService),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(20),                
            AllowInsecureHttp = true
        };
    }

    public void ConfigureAuth(IAppBuilder app)
    {
        app.UseOAuthBearerTokens(OAuthOptions);
    }
}

Auth Provider

public class OAuthAppProvider : OAuthAuthorizationServerProvider
{
    private IClientService _clientService;
    public OAuthAppProvider(IClientService clientService)
    {
        _clientService = clientService;
    }

    public override Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
        return Task.Factory.StartNew(() =>
        {
            var username = context.UserName;
            var password = context.Password;
            Client client = _clientService.GetByCredentials(username, password);
            if (client != null)
            {
                var claims = new List<Claim>()
                {
                    new Claim(ClaimTypes.Name, client.Username),
                    new Claim(ClaimTypes.Role, client.Role)
                };

                ClaimsIdentity oAutIdentity = new ClaimsIdentity(claims, Startup.OAuthOptions.AuthenticationType);
                context.Validated(new AuthenticationTicket(oAutIdentity, new AuthenticationProperties() { }));
            }
            else
            {
                context.SetError("invalid_grant", "Error with provided Username or Password.");
            }
        });
    }

    public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
    {
        if (context.ClientId == null)
        {
            context.Validated();
        }
        return Task.FromResult<object>(null);
    }
}

0 个答案:

没有答案