首页 > 其他分享 >338 Authorization with JWT

338 Authorization with JWT

时间:2024-07-01 21:57:59浏览次数:3  
标签:338 builder JWT headers token import new options Authorization

步骤

1、客户端添加headers

cities.service.ts

import { Injectable } from '@angular/core';
import { City } from "../models/city";
import { HttpClient, HttpHeaders } from "@angular/common/http";
import { Observable } from "rxjs";

const API_BASE_URL: string = "https://localhost:7173/api/";

@Injectable({
  providedIn: 'root'
})
export class CitiesService {
  cities: City[] = [];

  constructor(private httpClient: HttpClient) {
  }

  public getCities(): Observable<City[]> {
    let headers = new HttpHeaders();
    headers = headers.append("Authorization", `Bearer ${localStorage["token"]}`);

    return this.httpClient.get<City[]>(`${API_BASE_URL}v1/cities`, { headers: headers })
  }

  public postCity(city: City): Observable<City> {
    let headers = new HttpHeaders();
    headers = headers.append("Authorization", `Bearer ${localStorage["token"]}`);

    return this.httpClient.post<City>(`${API_BASE_URL}v1/cities`, city, { headers: headers })
  }

  public putCity(city: City): Observable<string> {
    let headers = new HttpHeaders();
    headers = headers.append("Authorization", `Bearer ${localStorage["token"]}`);

    return this.httpClient.put<string>(`${API_BASE_URL}v1/cities/${city.cityID}`, city, { headers: headers })
  }

  public deleteCity(cityID: string | null): Observable<string> {
    let headers = new HttpHeaders();
    headers = headers.append("Authorization", `Bearer ${localStorage["token"]}`);

    return this.httpClient.delete<string>(`${API_BASE_URL}v1/cities/${cityID}`, { headers: headers })
  }
}

2、Logout清除token

app.component.ts添加localStorage.removeItem("token");

import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { AccountService } from './services/account.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  constructor(public accountService: AccountService, private router: Router) { }


  onLogOutClicked() {
    this.accountService.getLogout().subscribe({
      next: (response: string) => {
        this.accountService.currentUserName = null;
        localStorage.removeItem("token");

        this.router.navigate([ '/login' ]);
      },

      error: (error: any) => {
        console.log(error);
      },

      complete: () => { },
    });
  }
}

3、服务器验证Token

CitiesManager.WebAPI项目安装如下NuGet包

<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.6" />

Program.cs

//JWT
builder.Services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
    options.TokenValidationParameters = new TokenValidationParameters()
    {
        ValidateAudience = true,
        ValidAudience = builder.Configuration["Jwt: Audience"],
        ValidateIssuer = true,
        ValidIssuer = builder.Configuration["Jwt: Issuer"],
        ValidateLifetime = true,
        ValidateIssuerSigningKey = true,
        IssuerSigningKey = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]))
    };
});

builder.Services.AddAuthorization(options =>
{

});

var app = builder.Build();

全局应用到Controller(也可以DataAnnotation应用到需要的Controller)

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.


builder.Services.AddControllers(options =>
{
    options.Filters.Add(new ProducesAttribute("application/json")); //Response Body
    options.Filters.Add(new ConsumesAttribute("application/json")); //Request Body

    //JWT-Authorization policy
    var policy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();
    options.Filters.Add(new AuthorizeFilter(policy));

}).AddXmlSerializerFormatters();

排除在外可以添加[AllowAnonymous]

Gitee获取源码:

https://gitee.com/huang_jianhua0101/asp.-net-core-8.git

标签:338,builder,JWT,headers,token,import,new,options,Authorization
From: https://blog.csdn.net/KevinHuang2088/article/details/140110554

相关文章

  • 在IdentityServer4生成的JWT中添加一个自定义的Claim,用于ABP框架中要用到的token信息
    用过IdentityServer4或者熟悉ASP.NETCore认证的都应该知道有Claim,如何理解ids4中的Claim?这里可以理解为声明,我们每个用户都有多个Claim,每个Claim声明了用户的某个信息比如:Role=Admin,UserID=1000等等,这里Role,UserID每个都是用户的Claim,都是表示用户信息的单元 ,我们不妨把它称为......
  • 升级.Net8后Jwt密钥长度要求大于32的问题
    原因前段时间将项目升级到.net8后,提示jwt密钥长度太短了,这咋办,我解决1. 最简单的办法,把密钥长度加长2. 如果你的项目只需要验证token,而不需要生成,就:SymmetricSecurityKeyExtendKeyLengthIfNeeded(SymmetricSecurityKeykey,intminLenInBytes){......
  • JWT登录认证
    JWT登录认证导入jwt依赖<dependency><groupId>io.jsonwebtoken</groupId><artifactId>jjwt</artifactId><version>0.9.1</version></dependency>写个jwt工具类publicclassJwtUtil{//有......
  • .NET 6 Swagger+JWT 配置
    1.1封装一个SwaggerExtend类(包含JWT配置)///<summary>///Swagger静态类///</summary>publicstaticclassSwaggerExtend{///<summary>///添加服务:swagger///</summary>///<paramname=&qu......
  • 闲鱼面试:说说JWT工作原理?
    JWT(JSONWebToken)一种开放的标准规范(RFC7519),用于在网络上安全的传输信息,通常被用于身份验证。简单来说,你可以把JWT想象成一张小巧的、自包含的电子通行证。这张通行证里面包含了用户的身份信息,就像你在某个俱乐部的会员卡,上面有你的名字、会员等级等信息,拿着这张卡,你就能证......
  • 数位统计DP——AcWing 338. 计数问题
    数位统计DP定义数位DP(DigitalDP)是一种用于解决与数字的数位相关问题的动态规划算法。它将数字的每一位看作一个状态,通过转移状态来计算满足特定条件的数字个数或其他相关统计信息。运用情况统计满足特定条件的数字个数,例如在给定范围内有多少个数字满足某些数位特征。计算......
  • 通过获取的jwt认证token,实现自动登录django-admin后台
    视图层fromrest_framework_simplejwt.tokensimportAccessTokenfromdjango.middleware.csrfimportget_tokenfromdjango.contrib.authimportloginclassJwtToSessionView(GenericViewSet):@action(methods=['GET'],detail=False)defset(self,......
  • session、cookies、tonken以及JWT的定义以及区别
    session概述Session用于记录用户的状态。Session指的是一段时间内,单个客户端与Web服务器的一连串相关的交互过程。在一个Session中,客户可能会多次请求访问同一个资源,也有可能请求访问各种不同的服务器资源。Session是由服务器端创建的原理Session会为每一次会话分配一个S......
  • Apple - Authorization Services Programming Guide
    本文翻译整理自:AuthorizationServicesProgrammingGuide(更新日期:2011-10-19https://developer.apple.com/library/archive/documentation/Security/Conceptual/authorization_concepts/01introduction/introduction.html#//apple_ref/doc/uid/TP30000995文章目录一......
  • SpringBoot整合JWT(JSON Web Token)生成token与验证
    目录JWT什么是JWTJWT使用流程确定要传递的信息:生成JWT:JWT传输:客户端保存JWT:客户端发送JWT:服务器验证JWT:服务器响应:Token的使用示例:工具类R结果集返回一个生成的token创建拦截器JWT什么是JWTJWT(JSONWebToken)是是目前最流行的跨域认证解决方案。它通常被......