如何从ASP.net Web API发送令牌以响应js?

时间:2018-04-18 06:26:02

标签: reactjs authentication asp.net-web-api jwt

我想使用web api在react js中实现JWT身份验证。

我已在web api中创建了JWT身份验证。

当我测试它时,它在Postman上完全正常。

当我使用反应js时,API正在被攻击。

现在的问题是如何发送令牌以响应js以及如何在react js中获取令牌

这是我在web api中的登录控制器

using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Security.Claims;
using System.Web;
using System.Web.Http;
using System.Web.Http.Cors;
using WEBAPI_JWT_Authentication.Models;


namespace WEBAPI_JWT_Authentication.Controllers
{
    [EnableCors(origins: "*", headers: "*", methods: "*")]
    public class LoginController : ApiController
    {
        [HttpPost]
        public IHttpActionResult Authenticate([FromBody] LoginRequest login)
        {
            var loginResponse = new LoginResponse { };
            LoginRequest loginrequest = new LoginRequest { };
            loginrequest.Username = login.Username.ToLower();
            loginrequest.Password = login.Password;

            IHttpActionResult response;
            HttpResponseMessage responseMsg = new HttpResponseMessage();
            bool isUsernamePasswordValid = false;       

            if(login != null)
            isUsernamePasswordValid=loginrequest.Password=="test" ? true:false;
            // if credentials are valid
            if (isUsernamePasswordValid)
            {
                string token = createToken(loginrequest.Username);
                var responseJSON = token;
                //return the token
                return Ok(responseJSON);
            }
            else
            {
                // if credentials are not valid send unauthorized status code in response
                loginResponse.responseMsg.StatusCode = HttpStatusCode.Unauthorized;
                response = ResponseMessage(loginResponse.responseMsg);
                return response;
            }
        }

        private string createToken(string username)
        {
            //Set issued at date
            DateTime issuedAt = DateTime.UtcNow;
            //set the time when it expires
            DateTime expires = DateTime.UtcNow.AddDays(7);

            //http://stackoverflow.com/questions/18223868/how-to-encrypt-jwt-security-token
            var tokenHandler = new JwtSecurityTokenHandler();

            //create a identity and add claims to the user which we want to log in
            ClaimsIdentity claimsIdentity = new ClaimsIdentity(new[]
            {
                new Claim(ClaimTypes.Name, username)                
            });

            const string sec = "401b09eab3c013d4ca54922bb802bec8fd5318192b0a75f201d8b3727429090fb337591abd3e44453b954555b7a0812e1081c39b740293f765eae731f5a65ed1";
            var now = DateTime.UtcNow;
            var securityKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(System.Text.Encoding.Default.GetBytes(sec));
            var signingCredentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(securityKey,Microsoft.IdentityModel.Tokens.SecurityAlgorithms.HmacSha256Signature);


            //create the jwt
            var token =
                (JwtSecurityToken)
                    tokenHandler.CreateJwtSecurityToken(issuer:"http://localhost:50191",audience:"http://localhost:50191",
                        subject: claimsIdentity, notBefore: issuedAt, expires: expires, signingCredentials: signingCredentials);
            var tokenString = tokenHandler.WriteToken(token);

            return tokenString;
        }
    }
}

这是我在react js

中获取令牌的地方
function login(username, password) {
    return fetch(`${API_URL}/Login`, {username, passowrd})
        .then(response => {
            debugger;
            if (!response.ok) {
                return response;
            }

            return response.json();
        })
        .then(user => {
            debugger;
            // login successful if there's a jwt token in the response
            if (user && user.token) {
                // store user details and jwt token in local storage to keep user logged in between page refreshes
                localStorage.setItem('user', JSON.stringify(user));
            }

            return user;
        });
}

如果有人知道如何发送令牌以响应js以及如何在反应js中获取该令牌,那么请告诉我们。

1 个答案:

答案 0 :(得分:0)

我的方法是创建一个 Response

public class Response
{
    public string Status { get; set; }
    public string Message { get; set; }
    public object Token { get; set; }
}

根据您的需要,您需要在此类中定义什么,对于我来说,状态消息用于将进度状态更新到前端。

您将 tokendictionary 存储在Response类中,并将其返回给该函数。可以说:

[HttpPost]
        public IHttpActionResult Authenticate([FromBody] LoginRequest login)
        {
            var loginResponse = new LoginResponse { };
            LoginRequest loginrequest = new LoginRequest { };
            loginrequest.Username = login.Username.ToLower();
            loginrequest.Password = login.Password;
        IHttpActionResult response;
        HttpResponseMessage responseMsg = new HttpResponseMessage();
        bool isUsernamePasswordValid = false;       

        if(login != null)
        isUsernamePasswordValid=loginrequest.Password=="test" ? true:false;
        // if credentials are valid
        if (isUsernamePasswordValid)
        {
            string token = createToken(loginrequest.Username);
            Response Resp = new Response
            {
                Status = "Success",
                Message = "User Login Successfully Change the Status Message here",
                Token = tokenDictonary, //where you return token
            };
            return 
        }
        else
        {
            // if credentials are not valid send unauthorized status code in response
            loginResponse.responseMsg.StatusCode = HttpStatusCode.Unauthorized;
            response = ResponseMessage(loginResponse.responseMsg);
            return response;
        }
    }

在前端,您将获取api。 我向您展示 axios 示例

axios.post('http://yoururl', {
      Token: this.state.Token,
    })
      .then(result => {
        if (result.data.Status === 'Success') {
          localStorage.setItem('Nameyourvariablehere', result.data.Token.tokentype);
// generate more if your token has more field

然后您可以通过 getItem setItem 检查您的 localStorage ,我相信您知道以下步骤的操作< / p>

实际上,创建令牌的方式与我的不同,我有点遵循example