using FakeXiecheng.API.Dtos;
using FakeXiecheng.API.Models;
using FakeXiecheng.API.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
namespace FakeXiecheng.API.Controllers
{
[ApiController]
[Route("auth")] //新建空的class ,命名為AuthenticateController ,繼承ControllerBase这溅, 配置一級路由
public class AuthenticateController : ControllerBase
{
private readonly IConfiguration _configuration; //加載配置文件
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly ITouristRouteRepository _touristRouteRepository;
public AuthenticateController(
IConfiguration configuration,
UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager,
ITouristRouteRepository touristRouteRepository
)
{//通過構(gòu)造方法加載數(shù)據(jù)
_configuration = configuration;
_userManager = userManager;
_signInManager = signInManager;
_touristRouteRepository = touristRouteRepository;
}
[AllowAnonymous]
[HttpPost("login")] //設(shè)置post方法的登錄路由
public async Task<IActionResult> login([FromBody] LoginDto loginDto)
{//使用異步的方法登錄纬朝,內(nèi)部請求必須要用await
// 1 驗(yàn)證用戶名密碼
var loginResult = await _signInManager.PasswordSignInAsync( //使用jwt自帶的方法驗(yàn)證賬號密碼傲茄,不需要寫任何業(yè)務(wù)
loginDto.Email,
loginDto.Password,
false,
false
);
if(!loginResult.Succeeded) //如果登錄狀態(tài)不成功困乒,返回錯(cuò)誤請求
{
return BadRequest();
}
var user = await _userManager.FindByNameAsync(loginDto.Email);
//jwt 用戶管理器獲取用戶
// 2 創(chuàng)建jwt
// header
var signingAlgorithm = SecurityAlgorithms.HmacSha256;//驗(yàn)簽算法
// payload
var claims = new List<Claim>
{
// sub
new Claim(JwtRegisteredClaimNames.Sub, user.Id),
//new Claim(ClaimTypes.Role, "Admin")
};
var roleNames = await _userManager.GetRolesAsync(user);//使用jwt用戶管理器獲取用戶權(quán)限列表
foreach(var roleName in roleNames)
{
var roleClaim = new Claim(ClaimTypes.Role, roleName);
claims.Add(roleClaim); //遍歷權(quán)限依次添加到內(nèi)容主體
}
// signiture
var secretByte = Encoding.UTF8.GetBytes(_configuration["Authentication:SecretKey"]);
//讀取配置文件中的SecretKey迷捧,編碼
var signingKey = new SymmetricSecurityKey(secretByte);
//進(jìn)行對稱加密算法加密
var signingCredentials = new SigningCredentials(signingKey, signingAlgorithm);
//生成簽名證書(1.加密key 2.指定簽名算法)
var token = new JwtSecurityToken(
issuer: _configuration["Authentication:Issuer"],
audience: _configuration["Authentication:Audience"],
claims,
notBefore: DateTime.UtcNow,
expires: DateTime.UtcNow.AddDays(1),
signingCredentials //激光防偽標(biāo)志
) ;
var tokenStr = new JwtSecurityTokenHandler().WriteToken(token); //將token對象轉(zhuǎn)成亂碼
// 3 return 200 ok + jwt
return Ok(tokenStr);
}
[AllowAnonymous]
[HttpPost("register")] //設(shè)置注冊接口路由
public async Task<IActionResult> Register([FromBody] RegisterDto registerDto)
{
// 1 使用用戶名創(chuàng)建用戶對象
var user = new ApplicationUser()
{
UserName = registerDto.Email,
Email = registerDto.Email
};
// 2 hash密碼军拟,保存用戶
var result = await _userManager.CreateAsync(user, registerDto.Password);
if(!result.Succeeded)
{
return BadRequest();
}
// 3 初始化購物車
var shoppingCart = new ShoppingCart()
{
Id = Guid.NewGuid(),
UserId = user.Id
};
await _touristRouteRepository.CreateShoppingCart(shoppingCart);
await _touristRouteRepository.SaveAsync();
// 4 return
return Ok();
}
}
}
jwt 模式下實(shí)現(xiàn)token授權(quán)的登錄注冊
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
- 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來拳喻,“玉大人哭当,你說我怎么就攤上這事∪叱海” “怎么了钦勘?”我有些...
- 文/不壞的土叔 我叫張陵,是天一觀的道長亚亲。 經(jīng)常有香客問我彻采,道長,這世上最難降的妖魔是什么捌归? 我笑而不...
- 正文 為了忘掉前任肛响,我火速辦了婚禮,結(jié)果婚禮上惜索,老公的妹妹穿的比我還像新娘特笋。我一直安慰自己,他們只是感情好巾兆,可當(dāng)我...
- 文/花漫 我一把揭開白布猎物。 她就那樣靜靜地躺著虎囚,像睡著了一般。 火紅的嫁衣襯著肌膚如雪蔫磨。 梳的紋絲不亂的頭發(fā)上淘讥,一...
- 文/蒼蘭香墨 我猛地睜開眼魄揉,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了拭宁?” 一聲冷哼從身側(cè)響起洛退,我...
- 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎杰标,沒想到半個(gè)月后兵怯,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
- 正文 獨(dú)居荒郊野嶺守林人離奇死亡腔剂,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
- 正文 我和宋清朗相戀三年媒区,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片掸犬。...
- 正文 年R本政府宣布介褥,位于F島的核電站座掘,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏柔滔。R本人自食惡果不足惜溢陪,卻給世界環(huán)境...
- 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望睛廊。 院中可真熱鬧形真,春花似錦、人聲如沸喉前。這莊子的主人今日做“春日...
- 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至裕便,卻和暖如春绒净,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背偿衰。 一陣腳步聲響...
- 正文 我出身青樓缤言,卻偏偏與公主長得像,于是被迫代替她去往敵國和親视事。 傳聞我的和親對象是個(gè)殘疾皇子胆萧,可洞房花燭夜當(dāng)晚...
推薦閱讀更多精彩內(nèi)容
- 更多最新技術(shù)文章歡迎大家訪問我的個(gè)人博客○( ^皿^)っ豆腐別館 上文總覽篇中,相信大家已經(jīng)對接下來要做的事情有了...
- 1. 搭建一個(gè)最簡單的接口示例 創(chuàng)建一個(gè)項(xiàng)目根目錄 express 文件夾 安裝 express 的下一個(gè)版本(5...
- 閱讀本章節(jié)需要掌握springsecurity、oauth2協(xié)議虏辫、jwt 本次測試使用oauth2的授權(quán)碼模式進(jìn)行...
- 最近調(diào)試的項(xiàng)目砌庄,授權(quán)的方式使用的JWT 1.AFNetworking設(shè)置Bearer Token羹唠,通過網(wǎng)關(guān)驗(yàn)證 用...