加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net – 如何使用JWT对角度SPA的Web Api 2进行用户身份验证?

发布时间:2020-12-16 03:29:31 所属栏目:asp.Net 来源:网络整理
导读:我正在尝试将AngularJS单页面应用程序(SPA)中的身份验证设置为基于OWIN构建的Web Api.这是我的…… 这是登录功能(API中的AuthenticationController上的POST操作) public HttpResponseMessage login(Credentials creds) { if (creds.Password == "password" c
我正在尝试将AngularJS单页面应用程序(SPA)中的身份验证设置为基于OWIN构建的Web Api.这是我的……

这是登录功能(API中的AuthenticationController上的POST操作)

public HttpResponseMessage login(Credentials creds)
    {
        if (creds.Password == "password" && creds.Username.ToLower() == "username")
        {
            var user = new User { UserId = 101,Name = "John Doe",Role = "admin" };

            var tokenDescriptor = new SecurityTokenDescriptor()
            {
                Subject = new ClaimsIdentity(new[]
                {
                    new Claim(ClaimTypes.Name,user.Name),new Claim(ClaimTypes.Role,user.Role)
                }),AppliesToAddress = "http://localhost:/8080",TokenIssuerName = "myApi",SigningCredentials = new SigningCredentials(new InMemorySymmetricSecurityKey(TestApp.Api.Startup.GetBytes("ThisIsTopSecret")),"http://www.w3.org/2001/04/xmldsig-more#hmac-sha256","http://www.w3.org/2001/04/xmlenc#sha256")
            };

            var tokenHandler = new JwtSecurityTokenHandler();
            var token = tokenHandler.CreateToken(tokenDescriptor);
            var tokenString = tokenHandler.WriteToken(token);

            return Request.CreateResponse<LoginResponse>(HttpStatusCode.Accepted,new LoginResponse { User = user,AuthToken = tokenString });
        }

        return Request.CreateResponse(HttpStatusCode.Unauthorized);
    }

这是我的OWIN启动配置

public void Configuration(IAppBuilder app)
    {
        app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

        HttpConfiguration config = new HttpConfiguration();
        config.Routes.MapHttpRoute(
            name: "Default",routeTemplate: "{controller}"
        );

        var jsonSettings = config.Formatters.JsonFormatter.SerializerSettings;
        jsonSettings.Formatting = Formatting.Indented;
        jsonSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

        app.UseWebApi(config);

        app.UseJwtBearerAuthentication(
        new JwtBearerAuthenticationOptions
        {
            AuthenticationMode = AuthenticationMode.Active,AllowedAudiences = new[] { "http://localhost:8080" },IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
            {
                new SymmetricKeyIssuerSecurityTokenProvider("myApp",TestApp.Api.Startup.GetBytes("ThisIsTopSecret"))
            }
        });
    }

这是我用来调用具有Authorized属性的API中的控制器的角度代码.

$http({ method: 'GET',url: 'http://localhost:5000/Admin',headers: { 'Content-Type': 'application/json','Authorization': 'Bearer ' + Session.token }})
          .then(function (res) {
              return res.data;
          });

当我登录时,我将返回的令牌作为字符串.然后我将它存储在我的客户端Session中.然后我把它拿到我的标题中以备后续请求.

当我尝试在API中调用“授权”操作时,即使我的令牌通过请求的标头传入,我也会获得401响应.

我是JWT的新手,所以我可能完全偏离我的方法.任何建议都会很棒.

解决方法

我相信这是一个操作秩序的事情.将app.UseJwt语句移动到app.UseWebApi行上方.

app.UseJwtBearerAuthentication(
    new JwtBearerAuthenticationOptions
    {
        AuthenticationMode = AuthenticationMode.Active,IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
        {
            new SymmetricKeyIssuerSecurityTokenProvider("myApp",TestApp.Api.Startup.GetBytes("ThisIsTopSecret"))
        }
    });

 app.UseWebApi(config);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读