Retrieving User Info
Retrieving User Information
After successfully logging in with K12NET's Single Sign-On (SSO) system, it's crucial to retrieve and handle the user's information securely within your ASP.NET Core web application, "YourSite". The Signin-K12NET.cshtml
page and its code-behind demonstrate how to achieve this by capturing the authorization code, exchanging it for an access token, and finally fetching the user's details.
Process Overview
-
Capture the Authorization Code: The user is redirected back to your application with an authorization code appended to the query string. This code is crucial for the next step in the SSO process.
-
Exchange Code for Access Token: Use the authorization code to request an access token from K12NET's token endpoint. This token grants temporary access to the user's information.
-
Fetch User Information: With the access token, make a request to the
/userinfo
endpoint to retrieve the user's details.
Code Explanation
-
Initialization: The
Signin_K12NETModel
class starts by declaring necessary dependencies and properties for storing user information.private readonly IConfiguration Configuration; public Dictionary
UserInfo { get; set; } public Signin_K12NETModel(IConfiguration configuration) { Configuration = configuration; } -
OnGet Method: This async method is triggered upon page load. It performs the main operations for retrieving user info:
-
Extract Authorization Code: The code is extracted from the query string.
-
Get Access Token:
GetAccessTokenAsync
makes an HTTP POST request to the token endpoint with the authorization code and other required details to obtain an access token. -
Retrieve User Info:
GetUserInformationAsync
uses the access token to fetch the user's information from the/userinfo
endpoint. -
Deserialize and Store User Info: The user information JSON is deserialized into a dictionary and stored in
UserInfo
property for later use. -
Sign-In User: A new
ClaimsPrincipal
is created with claims extracted from the user info. The user is then signed in using cookie authentication, making them officially authenticated in your application.
public async Task OnGet() { var code = Request.Query["code"]; var accessToken = await GetAccessTokenAsync(code); var userInfo = await GetUserInformationAsync(accessToken); UserInfo = JsonSerializer.Deserialize
>(userInfo); await HttpContext.SignInAsync(new ClaimsPrincipal(new ClaimsIdentity(new[] { new Claim("K12NETID", UserInfo["ID"]), new Claim(ClaimTypes.Name, UserInfo["sub"]) }, "Cookies")), new AuthenticationProperties { IsPersistent = true, ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(60) }); } public async Task
GetAccessTokenAsync(string code) { var client = new HttpClient(); var tokenRequest = new Dictionary { ["client_id"] = Configuration.GetSection("K12NETPartnerInfo:client_id").Value, ["client_secret"] = Configuration.GetSection("K12NETPartnerInfo:client_secret").Value, ["grant_type"] = "authorization_code", ["code"] = code, ["redirect_uri"] = Configuration.GetSection("K12NETPartnerInfo:redirect_uri").Value }; var requestContent = new FormUrlEncodedContent(tokenRequest); var response = await client.PostAsync(Configuration.GetSection("K12NETPartnerInfo:url").Value + "/GWCore.Web/connect/token", requestContent); response.EnsureSuccessStatusCode(); var responseString = await response.Content.ReadAsStringAsync(); var tokenResponse = JsonSerializer.Deserialize >(responseString); return tokenResponse["access_token"].GetString(); } public async Task GetUserInformationAsync(string accessToken) { var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken); var response = await client.GetAsync(Configuration.GetSection("K12NETPartnerInfo:url").Value + "/GWCore.Web/connect/userinfo"); response.EnsureSuccessStatusCode(); var userInfo = await response.Content.ReadAsStringAsync(); return userInfo; } -
-
HTTP Client Configuration: Both
GetAccessTokenAsync
andGetUserInformationAsync
configure anHttpClient
instance to make requests to K12NET's endpoints, handling authorization and content negotiation.
Security and Privacy
This process ensures that sensitive information, like the authorization code and access token, is handled securely through HTTPS requests. Furthermore, user information is processed server-side, preventing exposure to the client.
Conclusion
By following the outlined steps and understanding the code structure, you can effectively integrate K12NET's SSO into "YourSite", allowing for a seamless and secure user authentication experience. This not only enhances the usability of your application but also leverages the robust security features of K12NET's platform.