ホームページ > バックエンド開発 > C++ > ASP.NET Core で AngularJS アプリケーション用にトークンベースの認証を実装するにはどうすればよいですか?

ASP.NET Core で AngularJS アプリケーション用にトークンベースの認証を実装するにはどうすればよいですか?

DDD
リリース: 2024-12-27 18:53:12
オリジナル
259 人が閲覧しました

How to Implement Token-Based Authentication in ASP.NET Core for an AngularJS Application?

ASP.NET Core のトークンベースの認証


シナリオ

があるとします。実装する ASP.NET Core アプリケーションAngularJS アプリケーションのトークンベースの認証。 AngularJS アプリケーションは、ユーザー名とパスワードを渡して特定の URL にリクエストを作成します。 Web API はユーザーを承認し、AngularJS アプリが後続のリクエストで使用するアクセス トークンを返します。

ASP.NET Core でトークンベースの認証を構成する方法

ASP.NET Core Web API アプリケーションをトークンベース用に構成するには認証:

1.定数の定義

トークンの対象者と発行者の定数を作成します:

const string TokenAudience = "Myself";
const string TokenIssuer = "MyProject";
ログイン後にコピー

2.サービスの構成

Startup.cs ファイルで、次の行を ConfigureServices メソッドに追加します。

var keySecret = authenticationConfiguration["JwtSigningKey"];
var symmetricKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(keySecret));

services.AddTransient(_ => new JwtSignInHandler(symmetricKey));

services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
})
    .AddJwtBearer(options =>
    {
        options.TokenValidationParameters.ValidateIssuerSigningKey = true;
        options.TokenValidationParameters.IssuerSigningKey = symmetricKey;
        options.TokenValidationParameters.ValidAudience = JwtSignInHandler.TokenAudience;
        options.TokenValidationParameters.ValidIssuer = JwtSignInHandler.TokenIssuer;
    });
ログイン後にコピー

3.認証のセットアップ

Startup.cs ファイルの、ユーザー情報を必要とするミドルウェアの前に次の行を追加します:

app.UseAuthentication();
ログイン後にコピー

4.トークンを構築します

JWT トークン生成を処理するクラスを作成します:

class JwtSignInHandler
{
    public const string TokenAudience = "Myself";
    public const string TokenIssuer = "MyProject";
    private readonly SymmetricSecurityKey key;

    public JwtSignInHandler(SymmetricSecurityKey symmetricKey)
    {
        this.key = symmetricKey;
    }

    public string BuildJwt(ClaimsPrincipal principal)
    {
        var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

        var token = new JwtSecurityToken(
            issuer: TokenIssuer,
            audience: TokenAudience,
            claims: principal.Claims,
            expires: DateTime.Now.AddMinutes(20),
            signingCredentials: creds
        );

        return new JwtSecurityTokenHandler().WriteToken(token);
    }
}
ログイン後にコピー

5.トークンを返す

トークンを返すコントローラー アクションで、BuildJwt メソッドを呼び出します。

[HttpPost]
public string AnonymousSignIn([FromServices] JwtSignInHandler tokenFactory)
{
    var principal = new System.Security.Claims.ClaimsPrincipal(new[]
    {
        new System.Security.Claims.ClaimsIdentity(new[]
        {
            new System.Security.Claims.Claim(System.Security.Claims.ClaimTypes.Name, "Demo User")
        })
    });
    return tokenFactory.BuildJwt(principal);
}
ログイン後にコピー

これらの手順により、ASP.NET Core Web APIアプリケーションはトークンベースの認証を使用するように構成され、AngularJS アプリケーションが保護されたリソースに安全にアクセスできるようになります。

以上がASP.NET Core で AngularJS アプリケーション用にトークンベースの認証を実装するにはどうすればよいですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート