.net token如何验证页面

2025-10-18 20:26:20

1、      我们知道WEB网站的身份验证一般通过session或者cookie完成的,登录成功后客户端发送的任何请求都带上cookie,服务端根据客户端发送来的cookie来识别用户。

    WEB API使用这样的方法不是很适合,于是就有了基于令牌的认证,使用令牌认证有几个好处:可扩展性、松散耦合、移动终端调用比较简单等等,别人都用上了,你还有理由不用吗?

    下面我们花个20分钟的时间来实现一个简单的WEB API token认证:

2、安装所需的NuGet包:

.net token如何验证页面

3、在项目根目录下添加Owin“Startup”类

4、using System;

using System.Web.Http;

using Owin;

using Microsoft.Owin;

using Microsoft.Owin.Security.OAuth;

using SqlSugar.WebApi;

[assembly: OwinStartup(typeof(WebApi.Startup))]

namespace WebApi

{

    public class Startup

    {

        public void Configuration(IAppBuilder app)

        {

            HttpConfiguration config = new HttpConfiguration();

            ConfigureOAuth(app);

            WebApiConfig.Register(config);

            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

            app.UseWebApi(config);

        }

        public void ConfigureOAuth(IAppBuilder app)

        {

            OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()

            {

                AllowInsecureHttp = true,

                TokenEndpointPath = new PathString("/token"),

                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),

                Provider = new SimpleAuthorizationServerProvider()

            };

            app.UseOAuthAuthorizationServer(OAuthServerOptions);

            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

        }

    }

}

5、      在项目根目录下添加验证类 SimpleAuthorizationServerProvider,为了简单用户的验证部分我们省略掉;

6、using System.Threading.Tasks;

using System.Security.Claims;

using Microsoft.Owin.Security.OAuth;

namespace WebApi

{

    /// <summary>

    /// Token验证

    /// </summary>

    public class SimpleAuthorizationServerProvider : OAuthAuthorizationServerProvider

    {

        public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)

        {

            await Task.Factory.StartNew(() => context.Validated());

        }

        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)

        {

            await Task.Factory.StartNew(() => context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" }));

            /*

             * 对用户名、密码进行数据校验

            using (AuthRepository _repo = new AuthRepository())

            {

                IdentityUser user = await _repo.FindUser(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("sub", context.UserName));

            identity.AddClaim(new Claim("role", "user"));

            context.Validated(identity);

        }

    }

}

7、让CORS起作用

       在ASP.NET Web API中启用OAuth的Access Token验证非常简单,只需在相应的Controller或Action加上[Authorize]标记

 [Authorize]        

 [HttpGet, Route("product/getList")]        

 public List<Entity.Sys_User> GetProductList()

{

      throw new NotImplementedException();

}

8、请求 Token

.net token如何验证页面

9、获取token, POST   http://localhost:23477/token

参数BODY x-www-form-urlencoded 格式:

grant_type=password

username=admin 

password=123456

返回状态200 结果为

.net token如何验证页面

10、调用api

只要在http请求头中加上Authorization:bearer Token就可以成功访问API就成功了:

GET   http://localhost:58192/api/testapi/testapi

Authorization : bearer T5jF97t5n-rBkWcwpiVDAlhzXtOvV7Jw2NnN1Aldc--xtDrvWtqLAN9hxJN3Fy7piIqNWeLMNm2IKVOqmmC0X5_s8MwQ6zufUDbvF4Bg5OHoHTKHX6NmZGNrU4mjpCuPLtSbT5bh_gFOZHoIXXIKmqD3Wu1MyyKKNhj9XPEIkd9bl4E9AZ1wAt4dyUxmPVA_VKuN7UvYJ97TkO04XyGqmXGtfVWKfM75mNVYNhySWTg

.net token如何验证页面

.net token如何验证页面

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢