如何让 Bear Token 在 Postman 中运行

How to make the Bear Token to be working in Postman

目标:
使用熊令牌访问控制器帐户中的方法测试。

问题:
当我使用 post man 时它不起作用。 我缺少代码的哪一部分?

其他:
在 VS 2019 和 Postman 中使用 asp.net core v3。

C#代码

代码:

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();

        // ---- \/ Related to GenerateJSONWebToken ------------------
        services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddJwtBearer(options =>
        {
            options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer = true,
                ValidateAudience = true,
                ValidateLifetime = true,
                ValidateIssuerSigningKey = true,
                ValidIssuer = Configuration["JwtIssuer"],
                ValidAudience = Configuration["JwtIssuer"],
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration.GetValue<string>("JwtSecretKey")))
            };
        });
        // ---- /\ Related to GenerateJSONWebToken ------------------

        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(
                Configuration.GetConnectionString("DefaultConnection")));

        services.AddIdentity<IdentityUser, IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();

        services.AddAuthorization(options =>
        {
            options.AddPolicy("IsAdminClaimAccess", policy => policy.RequireClaim("CanReadFoodmenu", "true"));


            options.AddPolicy("ThePolicy", policy => policy.RequireClaim("CanReadCheck"));
            options.AddPolicy("RoleBasedClaim", policy => policy.RequireClaim("CanReadBlog"));
        });
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseHttpsRedirection();

        app.UseRouting();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
}
public class ApplicationDbContext : IdentityDbContext
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }
}
{
    "ConnectionStrings": {
        "DefaultConnection": "Server=DESKTOP-234\MSSQLDEV2019;Database=AspnetIdentity;Trusted_Connection=True;MultipleActiveResultSets=true"
    },
    "Logging": {
        "LogLevel": {
            "Default": "Information",
            "Microsoft": "Warning",
            "Microsoft.Hosting.Lifetime": "Information"
        }
    },
    "AllowedHosts": "*",
    "JwtSecretKey": "travisgatesalksdjakljdkjsadfhkjsdfhjksdlfksdljfhsjkdlf-key",
    "JwtIssuer": "JwtRoleBasedAuth",
    "JwtAudience": "JwtRoleBasedAuth",
    "AppUrl": "http://localhost:4500"
}
[Route("api/[controller]")]
[ApiController]
[Authorize]
public class AccountController : ControllerBase
{
    private readonly SignInManager<IdentityUser> _signInManager;
    private readonly RoleManager<IdentityRole> _roleManager;
    private readonly UserManager<IdentityUser> _userManager;
    private Microsoft.Extensions.Configuration.IConfiguration _configuration { get; }

    public AccountController(
        SignInManager<IdentityUser> signInManager,
        RoleManager<IdentityRole> roleMgr,
        UserManager<IdentityUser> userManager,
        Microsoft.Extensions.Configuration.IConfiguration configuration)
    {
        this._signInManager = signInManager;
        this._roleManager = roleMgr;
        this._userManager = userManager;
        this._configuration = configuration;
    }

    [HttpPost("Login", Name = "Login")]
    [AllowAnonymous]
    public async Task<IActionResult> Login([FromBody] LoginViewModel model)
    {
        var result = await _signInManager.PasswordSignInAsync(model.Username, model.Password, false, lockoutOnFailure: false);

        if (result.Succeeded)
        {
            IdentityUser user = await _userManager.FindByEmailAsync(model.Username);

            var userRoleNames = await _userManager.GetRolesAsync(user);
            var userClaims = await _userManager.GetClaimsAsync(user).ConfigureAwait(false);

            User myUser = new User
            {
                Username = user.UserName,
                Token = GenerateJSONWebToken(userClaims),
                Claims = userClaims
            };
            return Ok(myUser);
        }
        throw new NotImplementedException();
    }

    private string GenerateJSONWebToken(IList<System.Security.Claims.Claim> claims)
    {
        var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration.GetValue<string>("JwtSecretKey")));
        var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

        var token = new JwtSecurityToken(
            _configuration.GetValue<string>("JwtIssuer"),
            claims: claims,
            expires: DateTime.Now.AddMinutes(120),
            signingCredentials: credentials);

        return new JwtSecurityTokenHandler().WriteToken(token);
    }

    // GET: api/<AccountController>
    [HttpGet]
    [Authorize]
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }

    [HttpGet("Test", Name = "Test")]
    [Authorize]
    public async Task<IActionResult> Test()
    {
        return Ok(new string[] { "22", "22" });
    }

    [Authorize]
    [HttpGet("Test2", Name = "Test2")]
    public async Task<IActionResult> Test2()
    {
        return Ok(new string[] { "444", "444" });
    }

    // GET api/<AccountController>/5
    [HttpGet("{id}")]
    public string Get(int id)
    {
        return "value";
    }
}

public class LoginViewModel
{
    public string Username { get; set; }
    public string Password { get; set; }
}

public class LoginQuery : User
{
    public string Password { get; set; }
}

public class User
{
    public string Username { get; set; }
    public string Token { get; set; }
    public IList<System.Security.Claims.Claim> Claims { get; set; }
}

CREATE TABLE [dbo].[AspNetRoleClaims](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [RoleId] [nvarchar](450) NOT NULL,
    [ClaimType] [nvarchar](max) NULL,
    [ClaimValue] [nvarchar](max) NULL,
 CONSTRAINT [PK_AspNetRoleClaims] PRIMARY KEY CLUSTERED 
(
    [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO

ALTER TABLE [dbo].[AspNetRoleClaims]  WITH CHECK ADD  CONSTRAINT [FK_AspNetRoleClaims_AspNetRoles_RoleId] FOREIGN KEY([RoleId])
REFERENCES [dbo].[AspNetRoles] ([Id])
ON DELETE CASCADE
GO

ALTER TABLE [dbo].[AspNetRoleClaims] CHECK CONSTRAINT [FK_AspNetRoleClaims_AspNetRoles_RoleId]
GO

CREATE TABLE [dbo].[AspNetRoles](
    [Id] [nvarchar](450) NOT NULL,
    [Name] [nvarchar](256) NULL,
    [NormalizedName] [nvarchar](256) NULL,
    [ConcurrencyStamp] [nvarchar](max) NULL,
 CONSTRAINT [PK_AspNetRoles] PRIMARY KEY CLUSTERED 
(
    [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO

CREATE TABLE [dbo].[AspNetUserClaims](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [UserId] [nvarchar](450) NOT NULL,
    [ClaimType] [nvarchar](max) NULL,
    [ClaimValue] [nvarchar](max) NULL,
 CONSTRAINT [PK_AspNetUserClaims] PRIMARY KEY CLUSTERED 
(
    [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO

ALTER TABLE [dbo].[AspNetUserClaims]  WITH CHECK ADD  CONSTRAINT [FK_AspNetUserClaims_AspNetUsers_UserId] FOREIGN KEY([UserId])
REFERENCES [dbo].[AspNetUsers] ([Id])
ON DELETE CASCADE
GO

ALTER TABLE [dbo].[AspNetUserClaims] CHECK CONSTRAINT [FK_AspNetUserClaims_AspNetUsers_UserId]
GO

CREATE TABLE [dbo].[AspNetUserLogins](
    [LoginProvider] [nvarchar](128) NOT NULL,
    [ProviderKey] [nvarchar](128) NOT NULL,
    [ProviderDisplayName] [nvarchar](max) NULL,
    [UserId] [nvarchar](450) NOT NULL,
 CONSTRAINT [PK_AspNetUserLogins] PRIMARY KEY CLUSTERED 
(
    [LoginProvider] ASC,
    [ProviderKey] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO

ALTER TABLE [dbo].[AspNetUserLogins]  WITH CHECK ADD  CONSTRAINT [FK_AspNetUserLogins_AspNetUsers_UserId] FOREIGN KEY([UserId])
REFERENCES [dbo].[AspNetUsers] ([Id])
ON DELETE CASCADE
GO

ALTER TABLE [dbo].[AspNetUserLogins] CHECK CONSTRAINT [FK_AspNetUserLogins_AspNetUsers_UserId]
GO

CREATE TABLE [dbo].[AspNetUserRoles](
    [UserId] [nvarchar](450) NOT NULL,
    [RoleId] [nvarchar](450) NOT NULL,
 CONSTRAINT [PK_AspNetUserRoles] PRIMARY KEY CLUSTERED 
(
    [UserId] ASC,
    [RoleId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO

ALTER TABLE [dbo].[AspNetUserRoles]  WITH CHECK ADD  CONSTRAINT [FK_AspNetUserRoles_AspNetRoles_RoleId] FOREIGN KEY([RoleId])
REFERENCES [dbo].[AspNetRoles] ([Id])
ON DELETE CASCADE
GO

ALTER TABLE [dbo].[AspNetUserRoles] CHECK CONSTRAINT [FK_AspNetUserRoles_AspNetRoles_RoleId]
GO

ALTER TABLE [dbo].[AspNetUserRoles]  WITH CHECK ADD  CONSTRAINT [FK_AspNetUserRoles_AspNetUsers_UserId] FOREIGN KEY([UserId])
REFERENCES [dbo].[AspNetUsers] ([Id])
ON DELETE CASCADE
GO

ALTER TABLE [dbo].[AspNetUserRoles] CHECK CONSTRAINT [FK_AspNetUserRoles_AspNetUsers_UserId]
GO


CREATE TABLE [dbo].[AspNetUsers](
    [Id] [nvarchar](450) NOT NULL,
    [UserName] [nvarchar](256) NULL,
    [NormalizedUserName] [nvarchar](256) NULL,
    [Email] [nvarchar](256) NULL,
    [NormalizedEmail] [nvarchar](256) NULL,
    [EmailConfirmed] [bit] NOT NULL,
    [PasswordHash] [nvarchar](max) NULL,
    [SecurityStamp] [nvarchar](max) NULL,
    [ConcurrencyStamp] [nvarchar](max) NULL,
    [PhoneNumber] [nvarchar](max) NULL,
    [PhoneNumberConfirmed] [bit] NOT NULL,
    [TwoFactorEnabled] [bit] NOT NULL,
    [LockoutEnd] [datetimeoffset](7) NULL,
    [LockoutEnabled] [bit] NOT NULL,
    [AccessFailedCount] [int] NOT NULL,
 CONSTRAINT [PK_AspNetUsers] PRIMARY KEY CLUSTERED 
(
    [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO

----

CREATE TABLE [dbo].[AspNetUserTokens](
    [UserId] [nvarchar](450) NOT NULL,
    [LoginProvider] [nvarchar](128) NOT NULL,
    [Name] [nvarchar](128) NOT NULL,
    [Value] [nvarchar](max) NULL,
 CONSTRAINT [PK_AspNetUserTokens] PRIMARY KEY CLUSTERED 
(
    [UserId] ASC,
    [LoginProvider] ASC,
    [Name] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO

ALTER TABLE [dbo].[AspNetUserTokens]  WITH CHECK ADD  CONSTRAINT [FK_AspNetUserTokens_AspNetUsers_UserId] FOREIGN KEY([UserId])
REFERENCES [dbo].[AspNetUsers] ([Id])
ON DELETE CASCADE
GO

ALTER TABLE [dbo].[AspNetUserTokens] CHECK CONSTRAINT [FK_AspNetUserTokens_AspNetUsers_UserId]
GO

Table [AspnetIdentity].[dbo].[AspNetRoleClaims]
 Id RoleId  ClaimType   ClaimValue
1   43655a2b-648a-4f06-886f-5089b4b3b1b4    ManagerPermissions  true

table [dbo].[AspNetRoles]

Id  Name    NormalizedName  ConcurrencyStamp
43655a2b-648a-4f06-886f-5089b4b3b1b4    Administrator   ADMINISTRATOR   81e0bb78-a6a1-49d2-a5aa-f45d2897f2bf

table [dbo].[AspNetUserClaims]

Id  UserId  ClaimType   ClaimValue
1   77d2edc1-e526-455e-8382-bd052319926a    DateOfJoining   09/25/1984
2   77d2edc1-e526-455e-8382-bd052319926a    IsAdmin true
3   722b8d95-9032-4436-9431-8d53061d6896    IsAdmin false
4   722b8d95-9032-4436-9431-8d53061d6896    DateOfJoining   09/01/2018
5   722b8d95-9032-4436-9431-8d53061d6896    IsHR    true

FROM [AspnetIdentity].[dbo].[AspNetUserRoles]

UserId  RoleId
77d2edc1-e526-455e-8382-bd052319926a    43655a2b-648a-4f06-886f-5089b4b3b1b4

    FROM [AspnetIdentity].[dbo].[AspNetUsers]
    
    Id  UserName    NormalizedUserName  Email   NormalizedEmail EmailConfirmed  PasswordHash    SecurityStamp   ConcurrencyStamp    PhoneNumber PhoneNumberConfirmed    TwoFactorEnabled    LockoutEnd  LockoutEnabled  AccessFailedCount
    722b8d95-9032-4436-9431-8d53061d6896    rakesh@gmail.com    RAKESH@GMAIL.COM    rakesh@gmail.com    RAKESH@GMAIL.COM    0   AQAAAAEAACcQAAAAEMIcrci3D/DwN+47lVAtR/ErkYu27QPL2N8Irq03Tmd/aKmQhxzA5gTBwDho8H92fg==    KYW7FPEAQAJ3ONOHH6TZWMSYI3OZNT2A    1482012f-385c-4f91-a7b9-0995ac28e5d0    NULL    0   0   NULL    1   0
    77d2edc1-e526-455e-8382-bd052319926a    jignesh@gmail.com   JIGNESH@GMAIL.COM   jignesh@gmail.com   JIGNESH@GMAIL.COM   0   AQAAAAEAACcQAAAAEPr7pYdx44GFW9dsAEAhC9TFg/3WL7EAICskI/MqW7MChKO1NsqNQ7ppRAj/UaGkFA==    677ZDX35TK44NOAI7VBUYBP4RQRZRP5I    e80a033e-1a4d-4d66-abb5-7aa674edc357    NULL    0   0   NULL    1   0

我假设它工作正常,但在 Postman 中不起作用。如果是这样,那么您就缺少一个“bearer”字符串。

在 postman 中,授权部分只是一种 shorthand 添加以下内容的方法 Header:

"Authorization" : "{your token}"

您遇到的问题是不记名令牌实际上需要具有字面意思的单词 bearer

"Authorization" : "bearer {your token}"

有人告诉我需要申请“UseAuthentication()”

您需要添加中间件:

app.UseAuthentication();

在你

之前
app.UseAuthorization();