WebApi配置OAuth2.0设置Token

首先是Startup.cs

    public void Configuration(IAppBuilder app)
    {
        var config = new HttpConfiguration();
        WebApiConfig.Register(config);
        app.UseCors(CorsOptions.AllowAll);
        ConfigureAuth(app);
        app.UseWebApi(config);
    }

然后把ConfigureAuth方法里面代码屏蔽,改成如下

        OAuthAuthorizationServerOptions OAuthOptions = new OAuthAuthorizationServerOptions()
        {
            AllowInsecureHttp = true,//允许客户端一http协议请求
            TokenEndpointPath = new PathString("/token"), //token请求的地址,即http://localhost:端口号/token;
            AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(600),
            Provider = new ApplicationOAuthProvider("PublicClientId") //提供具体的认证策略;
        };
        app.UseOAuthAuthorizationServer(OAuthOptions);
        app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

最后是GrantResourceOwnerCredentials方法(这里面生成Token)

		//API里面可以通过RequestContext.Principal.Identity.Name获取这里设置的用户标识
        ClaimsIdentity oAuthIdentity = new ClaimsIdentity(context.Options.AuthenticationType);
        oAuthIdentity.AddClaim(new Claim(ClaimTypes.Name, user.ID.ToString()));

        AuthenticationProperties properties = CreateProperties(user.UserName);
        AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
        context.Validated(ticket);
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值