问题
I created two applications in Azure portal: one is client app, and another one is web api. I'm getting accessToken in SPA and then using this token to make requests to web api. I created roles for web api app and then assigned one of these roles to myself.
Inside web api I can verify user roles for every endpoint using decorators [Authorize(Roles = "Reader, Editor, Admin")]
, but I also need access to these roles in my client application. I checked this accessToken using jwt.ms and it has "roles": ["Admin"]
after parsing. But how can I get these roles in client application using JS?
回答1:
If you just want to extract Claims from accessToken payload, just try the code below:
<html>
<body>
<div id="payload"></div>
</body>
<script src="https://cdn.jsdelivr.net/npm/js-base64@3.2.4/base64.min.js" ></script>
<script>
var token= "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6IkRJakFBSUpjNmZnMlkzd0dObkpRSEpXWjhXX1FGOG5Zd2lfVTFfOVhMejgifQ.eyJleHAiOjE1OTU1MTczNjMsIm5iZiI6MTU5NTUxMzc2MywidmVyIjoiMS4wIiwiaXNzIjoiaHR0cHM6Ly9zdGFudGVzdGIzYy5iMmNsb2dpbi5jb20vN2QzZDE4MjQtYTkyOC00ZWQ5LThlZDUtYjA0OTI5NTM4NTljL3YyLjAvIiwic3ViIjoiOGJiZDY3NDYtMDJjNy00MWE2LTk3Y2EtYzc0NWM4ZDI3YTIzIiwiYXVkIjoiNGVjZDM2MTYtM2IwNy00NjFiLTgzYjUtYmZhM2ZhZjAxYmY0IiwiYWNyIjoiYjJjXzFhX3NpZ251cF9zaWduaW4iLCJub25jZSI6ImRlZmF1bHROb25jZSIsImlhdCI6MTU5NTUxMzc2MywiYXV0aF90aW1lIjoxNTk1NTEzNzYzLCJvaWQiOiI4YmJkNjc0Ni0wMmM3LTQxYTYtOTdjYS1jNzQ1YzhkMjdhMjMiLCJuYW1lIjoic3RhbmxleSIsImdpdmVuX25hbWUiOiJnIiwiZmFtaWx5X25hbWUiOiJzdGFuIiwiZXh0ZW5zaW9uX3RuY2FjY2VwdGVkZGF0ZXRpbWUiOjE1ODk1NDk4NTUsImFjY291bnRFbmFibGVkIjp0cnVlLCJ0aWQiOiI3ZDNkMTgyNC1hOTI4LTRlZDktOGVkNS1iMDQ5Mjk1Mzg1OWMifQ.Fa5EX4b3Px5Xan_qs1a8I6DC8lLxu78AhyQu9-yqE68TCSrNt7QrAWbUPvFPC8TFErDb84FUPDvtLkVS7Q4mEM9dbAGRtxXoSkZa85TPLj6PxYmE61pONwwf971UZiFjLKjkhqVsbpC1Zbgvx5Z_vfFBlrlbxohzZHQuvBI6rqhLeZebvr9bitsIHgFvHJIh-6QgstII8ExQbXqLHzOB0E9e1nT4O7SaW4hnxEr-nKsnpsEbYZ-6LsIcR4svVyEsTp9_YoslU2hAHN0tLuJL-AR74wqUFjO79pUa3fCjiur207cEcvkthbahzeqVY-gqJGIGndZmxo3a3Rf0QEbWlg"
var token_parts = token.split(".")
var token_payload = JSON.parse(Base64.decode(token_parts[1]));
document.getElementById("payload").innerHTML = Base64.decode(token_parts[1]) + "</br> </br> name claim:" + token_payload.name;
</script>
</html>
Basically,a token is composed by 3 parts, separated by "." ,and the payload is stored in the second part, you can just Base64 decode it to get its content
来源:https://stackoverflow.com/questions/64658682/how-to-retrieve-user-roles-from-azule-ad-msal-accesstoken