我正在使用JWT创建ASP.net核心2.0 WEB API SSO身份验证。创建了一个示例Controller,它返回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);
}
}
}
答案 0 :(得分:0)
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>