一、首先写个webapi方法
[ApiController]
[Route("api/[controller]/[action]")]
public class UserController : ControllerBase
{
[HttpPost]
public string Login([FromBody] UserModel userModel)
//public string Login(string userName, string password)
{
//var Permission = "Permission";
var userId = "1";
//验证用户名密码
//创建JWT
// header
var signingAlgorithm = SecurityAlgorithms.HmacSha256;
// payload
var claims = new List<Claim>
{
// sub
new Claim(JwtRegisteredClaimNames.Sub,userId),
//new Claim(ClaimTypes.Role, "Admin")
};
// signiture
//var secretByte = Encoding.UTF8.GetBytes(_configuration["Authentication:SecretKey"]);
var secretByte = Encoding.UTF8.GetBytes("dengfenglaiSecretKey");
var signingKey = new SymmetricSecurityKey(secretByte);
var signingCredentials = new SigningCredentials(signingKey, signingAlgorithm);
var token = new JwtSecurityToken(
//颁发者
issuer: "dengfneglai", //_configuration["Authentication:Issuer"],
//接收者
audience: "zhuifengqu", //_configuration["Authentication:Audience"],
//自定义参数
claims,
notBefore: DateTime.UtcNow,
//过期时间
expires: DateTime.UtcNow.AddDays(1),
//签名证书
signingCredentials
);
var tokenStr = new JwtSecurityTokenHandler().WriteToken(token);
return tokenStr;
//return "哈哈哈";
}
[Serializable]
public class UserModel
{
public string userName { get; set; }
public string password { get; set; }
}
}
记得在Startup.cs中添加跨域
二、Vue登录页
<template>
<div class="login">
登录名:<input v-model="userName" type="text" placeholder="请输入用户名"/>
密码:<input v-model="password" type="password" placeholder="请输入密码"/>
<!-- <input v-model="message" /> -->
<button v-on:click="LoginClick">登录</button>
</div>
</template>
<!-- <script src="https://unpkg.com/axios/dist/axios.min.js"></script>-->
<script lang="ts">
import { computed } from '@vue/runtime-core'
import { createApp } from '@vue/runtime-dom'
import axios from 'axios'
// import qs from 'qs'
// Vue.prototype.$qs=qs
import { Vue } from 'vue-class-component'
export default{
// data(){
// return {
// userName:this.userName,
// password:this.password,
// message:'哈哈哈'
// }
// },
methods:{
LoginClick(){
if(!this.userName)
{
alert('请输入用户名');
// this.$message='请输入用户名';
return;
}
if(!this.password)
{
alert('请输入密码');
// this.$message='请输入密码';
return;
}
//let data = [{userName:"123",password:"789"}];
axios.post(`https://localhost:5001/api/user/Login`,{
userName: this.userName,
password: this.password
})
.then(res=>{
console.log('res=>',res);
})
.catch(function(error){
console.log(error)
})
// axios({
// url:'https://localhost:5001/weatherforecast',
// method:'GET',
// headers:{
// 'X-Client-Info':' {"a":"3000","ch":"1002","v":"5.0.4","e":"15611234619393093477584"}',
// 'X-Host': 'mall.film-ticket.film.list',
// },
// params:{
// userName:11111111,
// password:22222222
// }
// }).then(function(response){
// console.log(response);
// })
// .catch(function(error){
// console.log(error)
// })
}
}
}
</script>