![](/img/trans.png)
[英]How to authenticate MVC user login form with web API JWT token?
[英]How to consume and redirect JWT token URL \login\login.php?token=jwt.goes.here using c# web application
我正在使用JWT創建ASP.net core 2.0 WEB API SSO身份驗證。 創建了一個示例控制器,該控制器返回JWT令牌URL: http:// localhost:50311 / api / auth / token
任何建議或最好的方法來實施此將是一個很大的幫助。
namespace JWTwebAPI.Controllers
{
[Route("api/[controller]")]
public class AuthController : Controller
{
[HttpPost("token")]
public IActionResult Token()
{
//string tokenString = "test";
var claimsdata = new[] { new Claim(ClaimTypes.Name, "username") };
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("aabbccddeeffgghh"));
var signInCred = new SigningCredentials(key, SecurityAlgorithms.HmacSha256Signature);
var token = new JwtSecurityToken(
issuer: "mysite.com",
audience: "mysite.com",
expires: DateTime.Now.AddMinutes(20),
claims: claimsdata,
signingCredentials: signInCred
);
var tokenString = new JwtSecurityTokenHandler().WriteToken(token);
return Ok(tokenString);
}
}
}
ASP.NEt核心Web API代碼:
[HttpPost("GenerateToken")]
public IActionResult GenerateToken(string emailid)
{
//DB verification for email\username\password goes here
if (emailid.Equals("abcd@gmail.com"))
{
var claimsdata = new[]
{
new Claim("firstName", "FirstName"),
new Claim("LastName", "LasttName"),
new Claim("Email", "Email@email.com"),
new Claim(ClaimTypes.Email, "myemailid@email.com")
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("mysecretkeygoeshere"));
var signInCred = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
issuer: "mysite.com",
audience: "mysite.com",
expires: DateTime.Now.AddMinutes(20),
claims: claimsdata,
signingCredentials: signInCred
);
var tokenString = new JwtSecurityTokenHandler().WriteToken(token);
return Ok(new { jwt = tokenString });
}
// return BadRequest("Could not verify the user");
return Unauthorized();
}
HTML代碼在這里
<script type="text/javascript">
$(document).ready(function () {
$("#b1").click(function () {
var emailid = "abcd@gmail.com";
$.ajax({
type:"post",
dataType:'json',
data:{'emailid': emailid },
url: "http://localhost:xxxxx/api/Auth/GenerateToken",
}).done(function (data) {
var token = data.jwt
alert(token);
url = "xyz.com/login/index.php?
jwt=" + token
$(location).attr("href", url);
}).fail( function (error) {
console.log(error);
});
});
});
</script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.