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 = "" };
if (ModelState.IsValid)
{
if (viewModel.User == "wolf" && viewModel.PassWord == "")
{
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(), 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"
}
}

ASP.NET Core JWT认证授权介绍的更多相关文章

  1. 任务35:JWT 认证授权介绍

    任务35:JWT 认证授权介绍 应用场景主要是移动端或者PC端前后分离的场景 直接对客户端API的请求 例如访问admin/Index 没有权限返回403. 需要客户端手动的再发动请求,这是一个拿to ...

  2. ASP.NET Core - JWT认证实现

    一.JWT结构 JWT介绍就太多了,这里主要关注下Jwt的结构. Jwt中包含三个部分:Header(头部).Payload(负载).Signature(签名) Header:描述 JWT 的元数据的 ...

  3. CZGL.Auth: ASP.NET Core Jwt角色授权快速配置库

    CZGL.Auth CZGL.Auth 是一个基于 Jwt 实现的快速角色授权库,ASP.Net Core 的 Identity 默认的授权是 Cookie.而 Jwt 授权只提供了基础实现和接口,需 ...

  4. asp.net core-14.JWT认证授权 生成 JWT Token

    源码下载 语言组织能力不好 ,看这个 视频 用visual studio code打开文件,运行dotnet watch run 之后在postman里面去访问 拿到Token后

  5. Dotnet core使用JWT认证授权最佳实践(二)

    最近,团队的小伙伴们在做项目时,需要用到JWT认证.遂根据自己的经验,整理成了这篇文章,用来帮助理清JWT认证的原理和代码编写操作. 第一部分:Dotnet core使用JWT认证授权最佳实践(一) ...

  6. [转]三分钟学会.NET Core Jwt 策略授权认证

    [转]三分钟学会.NET Core Jwt 策略授权认证 一.前言# 大家好我又回来了,前几天讲过一个关于Jwt的身份验证最简单的案例,但是功能还是不够强大,不适用于真正的项目,是的,在真正面对复杂而 ...

  7. asp.net core 自定义认证方式--请求头认证

    asp.net core 自定义认证方式--请求头认证 Intro 最近开始真正的实践了一些网关的东西,最近写几篇文章分享一下我的实践以及遇到的问题. 本文主要介绍网关后面的服务如何进行认证. 解决思 ...

  8. Asp.Net Core 中IdentityServer4 授权中心之自定义授权模式

    一.前言 上一篇我分享了一篇关于 Asp.Net Core 中IdentityServer4 授权中心之应用实战 的文章,其中有不少博友给我提了问题,其中有一个博友问我的一个场景,我给他解答的还不够完 ...

  9. ASP.NET Core Token认证

    翻译:Token Authentication in ASP.NET Core 令牌认证(Token Authentication)已经成为单页应用(SPA)和移动应用事实上的标准.即使是传统的B/S ...

随机推荐

  1. SharePoint 2016 vs部署报错:无法加载功能xxx未能加载文件或程序集xxx或它的某一个依赖项。系统找不到指定的文件

    环境描述: SharePoint 2016 单服务器场模式 开发工具:VS2017,项目类型(功能):计时器. 问题描述: 在用vs直接部署时,报错如下: 部署步骤"激活功能"中出 ...

  2. VS2013中编译openssl的步骤和使用设置

    一.VS2013中编译openssl的步骤 版本号:openssl-1.0.1e 1.下载 OpenSSL http://www.openssl.org/,并解压到d:\openssl-1.0.1e目 ...

  3. (常用)loogging模块及(项目字典)

    loogging模块 '''import logging logging.debug('debug日志') # 10logging.info('info日志')   # 20logging.warni ...

  4. 【原创】Thinking in BigData (1)大数据简介

    提到大数据,就不得不提到Hadoop,提到Hadoop,就不得不提到Google公布的3篇研究论文:GFS.MapReduce.BigTable,Google确实是一家伟大的公司,开启了全球的大数据时 ...

  5. [转]MySQL常用Json函数和MySQL常用字符串函数

    MySQL常用Json函数:https://www.cnblogs.com/waterystone/p/5626098.html MySQL常用字符串函数:https://www.cnblogs.co ...

  6. winfrom里面打印类似小票

    首先在窗体上拖一个printDocument1控件和一个Button按钮,然后双击该控件的PrintPage事件,在事件里面复制下面代码: Pen blackPen = new Pen(Color.B ...

  7. (转)dubbo远程调用细节

    作者: 白文志 (来自开源社区) 服务提供者暴露一个服务的详细过程 上图是服务提供者暴露服务的主过程:首先ServiceConfig类拿到对外提供服务的实际类ref(如:HelloWorldImpl) ...

  8. npm dev run 报错

    解决办法: npm run dev --port 8088 Error: listen EACCES 0.0.0.0:8080at Object.exports._errnoException (ut ...

  9. LuoGu P2863 [USACO06JAN]牛的舞会The Cow Prom

    题目传送门 这个题还是个缩点的板子题...... 答案就是size大于1的强连通分量的个数 加一个size来统计就好了 #include <iostream> #include <c ...

  10. JsRender 前端渲染模板基础学习

    JsRender前端渲染模板 使用模板,可以预先自定义一些固定格式的HTML标签,在需要显示数据时,再传入真实数据组装并展示在Web页中:避免了在JS中通过“+”等手动分割.连接字符串的复杂过程:针对 ...