首页 文章

Angular2 - 使用登录和记住用户的应用程序

提问于
浏览
2

我正在尝试使用登录编写Angular 2(最终版本)中的应用程序并记住用户函数 . 我试着理解这个原理 .

1-用户输入他的登录名和密码,然后单击“连接”

2 webapeser上的Angular2请求,包含用户登录名和密码

3- Webservices创建一个令牌并将其存储在数据库中

4- Web服务将其发送回前端 .

But what the front does with the token ? Does it store it in localStorage ?

记住账号:

我已经读过这个话题What is the best way to implement "remember me" for a website?

我知道我们需要一个令牌并检查每个页面,如果这个令牌存在于cookie中,并且如果它在db中是相同的 .

But is it a different token than the one for the login ? Do I store it in the localStorage, sessionStorage or as a cookie ?

有人可以清楚地向我解释这一切吗?或者,如果您有任何明确的主题,教程或应用程序代码可以理解,我会非常高兴 .

1 回答

  • 3

    你可以看看JWT . 它的工作方式如下:

    服务器端:在您的Web服务或Web api中,登录控制器具有登录方法,该方法将接受用户名和密码并使用密钥生成令牌 .

    public string Login(string username, string password)
        {
            if (!VerifyUserPassword(username, password))
                return "Wrong access";
    
            List<Claim> claims = GetUserClaims(username);
    
            RSACryptoServiceProvider publicAndPrivate = new RSACryptoServiceProvider();
            publicAndPrivate.FromXmlString(File.ReadAllText(HostingEnvironment.MapPath("~/AppKey.xml")));
    
            JwtSecurityToken jwtToken = new JwtSecurityToken
            (
                issuer: "http://example.com",
                audience: "http://receiver.com",
                claims: claims,
                signingCredentials: new SigningCredentials(new RsaSecurityKey(publicAndPrivate), SecurityAlgorithms.RsaSha256Signature),
                expires: DateTime.Now.AddDays(1)
            );
    
            JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();
            string tokenString = tokenHandler.WriteToken(jwtToken);
    
            return tokenString;
        }
    

    请记住,此处使用的“AppKey.xml”文件是签署令牌的密钥,稍后将使用该令牌解码令牌 . 然后你可以创建customAuthorizeAttribute(在web api中不确定Web服务但应该有另一种方法)使用之前使用的密钥文件来验证令牌 .

    public class CustomAuthorizeAttribute : AuthorizeAttribute
    {
        public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
    
            AuthenticationHeaderValue token = actionContext.Request.Headers.Authorization;
            if (ValidateToken(token.ToString()))
                return;
            else
                throw new HttpResponseException(System.Net.HttpStatusCode.Unauthorized);
        }
    
        private bool ValidateToken(string TokenString)
        {
            bool result = false;
    
            try
            {
                SecurityToken securityToken = new JwtSecurityToken(TokenString);
                JwtSecurityTokenHandler securityTokenHandler = new JwtSecurityTokenHandler();
                RSACryptoServiceProvider publicAndPrivate = new RSACryptoServiceProvider();
    
                publicAndPrivate.FromXmlString(File.ReadAllText(HostingEnvironment.MapPath("~/AppKey.xml")));
    
                TokenValidationParameters validationParameters = new TokenValidationParameters()
                {
                    ValidIssuer = "http://example.com",
                    ValidAudience = "http://receiver.com",
                    IssuerSigningKey = new RsaSecurityKey(publicAndPrivate)
                };
    
                ClaimsPrincipal claimsPrincipal = securityTokenHandler.ValidateToken(TokenString, validationParameters, out securityToken);
    
                result = true;
            }
            catch (Exception ex)
            {
                result = false;
            }
    
            return result;
        }
    }
    

    所以现在无论你想在哪里使用授权,你都可以将这个customAuthoorize属性放在这样的方法上 .

    [CustomAuthorize]
        [HttpPost]
        public string TestAuthorization()
        {
            return "Success!";
        }
    

    客户端:在Angular2应用程序实现服务中,它会在向您发送请求之前将令牌注入到授权头中 .

    export class DataService {
    
    constructor(private http: Http) { }
    
    postService(url: string, body: any, options?: RequestOptions):     Observable<any> {
    let tempOptions: RequestOptions = options;
    
    if (tempOptions)
      tempOptions.headers.append('Authorization', localStorage.getItem("appToken"));
    else {
      tempOptions = new RequestOptions();
      let hd = new Headers();
      hd.append('Authorization', localStorage.getItem("appToken"));
    
      tempOptions.headers = hd;
    }
    
    return this.http.post(url, body, tempOptions).map((result: Response) => <any>result.json());
    
    }
    
    }
    

    然后在实际的组件类中简单地实现它 .

    Login() {
    this.myDataService.postService('http://YOURAPI/Login?username=xyz&password=xyz', null).subscribe(result => {
      let token = result;
      localStorage.setItem("appToken",token);
      this.message="Login successful";
    });
    

    在login方法中,将令牌存储到本地存储中,然后在通过刚创建的角度服务调用服务器方法时,将在请求头中注入授权令牌 .

    YourMethod() {
    this.myDataService.postService('http://YourAPI/TestAuthorization', null).subscribe(result => {
      this.message = result;
    });
    

    你们都准备好了!请享用!

相关问题