zoukankan      html  css  js  c++  java
  • ASP.NET Core JWT认证授权介绍

     

    using JWTWebApi.Models;
    using Microsoft.AspNetCore.Authentication.JwtBearer;
    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.IdentityModel.Tokens;
    using System.Text;
    
    namespace JWTWebApi
    {
        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.Configure<JwtSettings>(Configuration.GetSection("JwtSettings"));
                var jwtsettings = new JwtSettings();
                Configuration.Bind("JwtSettings", jwtsettings);
                services.AddAuthentication(options =>
                {
                    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
                }).AddJwtBearer(options =>
                {
                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidAudience = jwtsettings.Audience,
                        ValidIssuer = jwtsettings.Issuer,
                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtsettings.SecretKey))
    
                    };
                });
                services.AddMvc();
            }
    
            // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
            public void Configure(IApplicationBuilder app, IHostingEnvironment env)
            {
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                }
    
                app.UseAuthentication();
                app.UseMvc();
            }
        }
    }
    using JWTWebApi.Models;
    using JWTWebApi.ViewModel;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.Extensions.Options;
    using Microsoft.IdentityModel.Tokens;
    using System;
    using System.IdentityModel.Tokens.Jwt;
    using System.Security.Claims;
    using System.Text;
    
    namespace JWTWebApi.Controllers
    {
        [Route("api/[controller]")]
        public class AuthrozeController : Controller
        {
            private readonly JwtSettings _jwtSetting;
    
            public AuthrozeController(IOptions<JwtSettings> jwtSetting)
            {
                _jwtSetting = jwtSetting.Value;
            }
    
            [HttpGet]
            public IActionResult Token()
            {
                LoginViewModel viewModel = new LoginViewModel(){ User= "wolf",PassWord = "123456" };
                if (ModelState.IsValid)
                {
                    if (viewModel.User == "wolf" && viewModel.PassWord == "123456")
                    {
                        var claims = new Claim[]
                        {
                            new Claim(ClaimTypes.Name,"wolf"),
                            new Claim(ClaimTypes.Role,"admin"),
                        };
    
                        var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtSetting.SecretKey));
                        var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
                        var token = new JwtSecurityToken(_jwtSetting.Issuer, _jwtSetting.Audience, claims, DateTime.Now,
                            DateTime.Now.AddHours(30), creds);
                        return Ok(new { token = new JwtSecurityTokenHandler().WriteToken(token) });
                    }
    
                    return BadRequest();
                }
    
                return BadRequest();
            }
        }
    }
    {
      "Logging": {
        "IncludeScopes": false,
        "LogLevel": {
          "Default": "Debug",
          "System": "Information",
          "Microsoft": "Information"
        }
      },
      "JwtSettings": {
        "Issuer": "http://localhost:50443/",
        "Audience": "http://localhost:50443/",
        "SecretKey": "wolf123456789123456789"
      }
    }

  • 相关阅读:
    Oracle 建用户、 表空间脚本
    Java常见Jar包的用途
    EF:无法检查模型兼容性,因为数据库不包含模型元数据。
    Eclipse -Xms256M -Xmx640M -XX:PermSize=256m -XX:MaxPermSize=768m
    CentOS远程连接Windows操作系统
    spring boot / cloud (二十) 相同服务,发布不同版本,支撑并行的业务需求
    jvm
    jvm
    spring boot / cloud (十九) 并发消费消息,如何保证入库的数据是最新的?
    spring boot / cloud (十八) 使用docker快速搭建本地环境
  • 原文地址:https://www.cnblogs.com/lgxlsm/p/9111269.html
Copyright © 2011-2022 走看看