WebApi使用Token(OAUTH 2.0方式)


1.在項目中添加引用

Microsoft.AspNet.WebApi.Owin

Microsoft.Owin.Host.SystemWeb

Microsoft.Owin.Security.OAuth

Microsoft.Owin.Security.Cookies

Microsoft.AspNet.Identity.Owin

Microsoft.Owin.Cors

 

2.新建Startup類

 public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            ConfigAuth(app);

            HttpConfiguration config = new HttpConfiguration();
            WebApiConfig.Register(config);
            app.UseCors(CorsOptions.AllowAll);
            app.UseWebApi(config);
        }


        public void ConfigAuth(IAppBuilder app)
        {
            OAuthAuthorizationServerOptions option = new OAuthAuthorizationServerOptions()
            {
                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString("/token"), //獲取 access_token 授權服務請求地址
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1), //access_token 過期時間
                Provider = new SimpleAuthorizationServerProvider(), //access_token 相關授權服務
                RefreshTokenProvider = new SimpleRefreshTokenProvider() //refresh_token 授權服務
            };
            app.UseOAuthAuthorizationServer(option);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
        }
    }

 

3.OAuth身份認證,新建SimpleAuthorizationServerProvider類

public class SimpleAuthorizationServerProvider : OAuthAuthorizationServerProvider
{
    public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
    {
        context.Validated();
        return Task.FromResult<object>(null);
    }
    public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
        context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
        //驗證用戶名密碼
        AccountService accService = new AccountService();
        string md5Pwd = LogHelper.MD5CryptoPasswd(context.Password);
        IList<object[]> ul = accService.Login(context.UserName, md5Pwd);
        if (ul.Count() == 0)
        {
            context.SetError("invalid_grant", "The username or password is incorrect");
            return;
        }
        var identity = new ClaimsIdentity(context.Options.AuthenticationType);
        identity.AddClaim(new Claim("sub", context.UserName));
        identity.AddClaim(new Claim("role", "user"));
        context.Validated(identity);
    }
}

4.新建SimpleRefreshTokenProvider類

public class SimpleRefreshTokenProvider : AuthenticationTokenProvider
{
    private static ConcurrentDictionary<string, string> _refreshTokens = new ConcurrentDictionary<string, string>();
 
    /// <summary>
    /// 生成 refresh_token
    /// </summary>
    public override void Create(AuthenticationTokenCreateContext context)
    {
        context.Ticket.Properties.IssuedUtc = DateTime.UtcNow;
        context.Ticket.Properties.ExpiresUtc = DateTime.UtcNow.AddDays(60);
 
        context.SetToken(Guid.NewGuid().ToString("n"));
        _refreshTokens[context.Token] = context.SerializeTicket();
    }
 
    /// <summary>
    /// 由 refresh_token 解析成 access_token
    /// </summary>
    public override void Receive(AuthenticationTokenReceiveContext context)
    {
        string value;
        if (_refreshTokens.TryRemove(context.Token, out value))
        {
            context.DeserializeTicket(value);
        }
    }
}

5.在要加驗證的接口上加上[Authorize]標記

 [Authorize]
    public class DefaultController : ApiController
    {
        [HttpPost]
        public string getPost()
        {
            return JsonConvert.SerializeObject(new { state = 1, msg = "ok" });
        }

        [HttpGet]
        [AllowAnonymous]
        public string validatePass(string name)
        {
            return JsonConvert.SerializeObject(new { state = 2, msg = "validatePass_ok" });
        }
    }

6.傳入參數,獲取token

7.傳入access_token

 

 

 

參考原文地址:https://www.cnblogs.com/lnice/p/6857203.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM