详解在ASP.NET Core中使用Angular2以及与Angular2的Tok(3)

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { AppModule } from './app.module'; const platform = platformBrowserDynamic(); platform.bootstrapModule(AppModule);

基础整合完毕。

按F5 Debug一下,现在你能再浏览器中看到一句话:this is in angular 2

详解在ASP.NET Core中使用Angular2以及与Angular2的Tok

4.实现身份认证

废了半天劲,看着很傻,没有任何成就感。怎么办,让我们再深入一点,接下来我们来为Angular2完成一个Token base的身份验证,我会把Angular2的routing,data bind,service,http,等等你工作中最常用到的挨个演示一遍。

4.1.Server端

4.1.1.创建一些辅助类

4.1.1.1.在项目根目录下创建一个文件夹Auth,并添加RSAKeyHelper.cs以及TokenAuthOption.cs两个文件

•在RSAKeyHelper.cs中

using System.Security.Cryptography; namespace CSTokenBaseAuth.Auth { public class RSAKeyHelper { public static RSAParameters GenerateKey() { using (var key = new RSACryptoServiceProvider(2048)) { return key.ExportParameters(true); } } } }

•在TokenAuthOption.cs中

using System; using Microsoft.IdentityModel.Tokens; namespace CSTokenBaseAuth.Auth { public class TokenAuthOption { public static string Audience { get; } = "ExampleAudience"; public static string Issuer { get; } = "ExampleIssuer"; public static RsaSecurityKey Key { get; } = new RsaSecurityKey(RSAKeyHelper.GenerateKey()); public static SigningCredentials SigningCredentials { get; } = new SigningCredentials(Key, SecurityAlgorithms.RsaSha256Signature); public static TimeSpan ExpiresSpan { get; } = TimeSpan.FromMinutes(20); } }

4.1.1.2.在项目根目录下创建目录Model,并在其中添加RequestResult.cs,代码应该是这样。

public class RequestResult { public RequestState State { get; set; } public string Msg { get; set; } public Object Data { get; set; } } public enum RequestState { Failed = -1, NotAuth = 0, Success = 1 }

4.1.2更新Startup.cs

在ConfigureServices中添加如下代码:

services.AddAuthorization(auth => { auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder() .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme‌​) .RequireAuthenticatedUser().Build()); });

这里是添加身份认证服务

在Configure方法中添加如下代码:

app.UseExceptionHandler(appBuilder => { appBuilder.Use(async (context, next) => { var error = context.Features[typeof(IExceptionHandlerFeature)] as IExceptionHandlerFeature; //when authorization has failed, should retrun a json message to client if (error != null && error.Error is SecurityTokenExpiredException) { context.Response.StatusCode = 401; context.Response.ContentType = "application/json"; await context.Response.WriteAsync(JsonConvert.SerializeObject(new RequestResult { State = RequestState.NotAuth, Msg = "token expired" })); } //when orther error, retrun a error message json to client else if (error != null && error.Error != null) { context.Response.StatusCode = 500; context.Response.ContentType = "application/json"; await context.Response.WriteAsync(JsonConvert.SerializeObject(new RequestResult { State = RequestState.Failed, Msg = error.Error.Message })); } //when no error, do next. else await next(); }); });

本段是Handle当身份认证失败时抛出的异常,并返回合适的json

在相同的方法中添加另外一段代码:

app.UseJwtBearerAuthentication(new JwtBearerOptions() { TokenValidationParameters = new TokenValidationParameters() { IssuerSigningKey = TokenAuthOption.Key, ValidAudience = TokenAuthOption.Audience, ValidIssuer = TokenAuthOption.Issuer, // When receiving a token, check that we've signed it. ValidateIssuerSigningKey = true, // When receiving a token, check that it is still valid. ValidateLifetime = true, // This defines the maximum allowable clock skew - i.e. provides a tolerance on the token expiry time // when validating the lifetime. As we're creating the tokens locally and validating them on the same // machines which should have synchronised time, this can be set to zero. Where external tokens are // used, some leeway here could be useful. ClockSkew = TimeSpan.FromMinutes(0) } });

本段代码是应用JWTBearerAuthentication身份认证。

4.1.3.TokenAuthController.cs

在Controllers中新建一个Web API Controller Class,命名为TokenAuthController.cs。我们将在这里完成登录授权,

在同文件下添加两个类,分别用来模拟用户模型,以及用户存储,代码应该是这样:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wjyzyy.html