Xamarin Essentials - Cool Coders: Doumer - Me
Xamarin Essentials - Cool Coders: Doumer - Me
doumer.me
Uncategorized ,
08 Nov
1 of 10 11/28/2020, 4:08 PM
JWT Social auth with ASP.net core and Xamarin Essentials - Cool Coders about:reader?url=https://doumer.me/jwt-social-auth-with-asp-net-core...
which was added a few months ago is the Web Authenticator API.
This feature provides an abstraction layer over the process of
integrating authentication, calling the web browser, Managing
redirects e.t.c in our Xamarin App.
What we will do
First, we have to setup our client app on social media, in our case
we use Google and Facebook.
Then we get our app secrets and ids. This process is simple, and
well documented so, I just highlighted how to setup your redirect
URLs properly in the video associated to this post.
Then we create an ASP net core project and setup Cookie and
JWT authentication. Adding Google and Facebook auth with the
Credentials we saved earlier
1 services
2 .AddAuthentication(options =>
3 {
4 ///TODO: If you plan to use both cookie and JWT auth on this
API, you can use this attribute
5
6 ///[Authorize(AuthenticationSchemes =
JwtBearerDefaults.AuthenticationScheme)]
7
options.DefaultAuthenticateScheme =
8
JwtBearerDefaults.AuthenticationScheme;
9
options.DefaultScheme =
10 JwtBearerDefaults.AuthenticationScheme;
11 options.DefaultChallengeScheme =
12 JwtBearerDefaults.AuthenticationScheme;
13 })
14 .AddCookie(options =>
2 of 10 11/28/2020, 4:08 PM
JWT Social auth with ASP.net core and Xamarin Essentials - Cool Coders about:reader?url=https://doumer.me/jwt-social-auth-with-asp-net-core...
15 {
16 options.Events.OnRedirectToLogin =
options.Events.OnRedirectToAccessDenied = context =>
17
{
18
19 context.Response.StatusCode =
StatusCodes.Status401Unauthorized;
20
return Task.CompletedTask;
21
};
22
})
23
.AddJwtBearer(cfg =>
24
{
25
cfg.RequireHttpsMetadata = false;
26
cfg.SaveToken = true;
27
cfg.TokenValidationParameters = new
28
TokenValidationParameters
29
{
30
ValidIssuer = Configuration["JwtIssuer"],
31
ValidAudience = Configuration["JwtIssuer"],
32
IssuerSigningKey = new
33 SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JwtKey"])),
35 expire
36 };
37 })
38 .AddFacebook(facebook =>
39 {
40 facebook.AppId =
Configuration["Authentication:Facebook:AppId"];
41
facebook.AppSecret =
42
Configuration["Authentication:Facebook:AppSecret"];
facebook.SaveTokens = true;
})
.AddGoogle(google =>
google.ClientSecret =
3 of 10 11/28/2020, 4:08 PM
JWT Social auth with ASP.net core and Xamarin Essentials - Cool Coders about:reader?url=https://doumer.me/jwt-social-auth-with-asp-net-core...
Configuration["Authentication:Google:ClientSecret"];
google.ClientId =
Configuration["Authentication:Google:ClientId"];
google.SaveTokens = true;
Note: If you are using both Cookie and JWT auth scheme in your
API, you can chose which scheme to use in your controllers using
this attribute.
[Authorize(AuthenticationSchemes =
JwtBearerDefaults.AuthenticationScheme)]
await Request.HttpContext.ChallengeAsync(scheme);
4 of 10 11/28/2020, 4:08 PM
JWT Social auth with ASP.net core and Xamarin Essentials - Cool Coders about:reader?url=https://doumer.me/jwt-social-auth-with-asp-net-core...
== System.Security.Claims.ClaimTypes.GivenName)?.Value;
3 {
4 { "access_token", authToken.token },
5 { "refresh_token", string.Empty },
6 { "jwt_token_expires",
7 authToken.expirySeconds.ToString() },
8 { "email", email },
{ "firstName", givenName },
9
10 { "picture", picture },
{ "secondName", surName },
11
};
12
15 "&",
qs.Where(kvp =>
16
!string.IsNullOrEmpty(kvp.Value) && kvp.Value != "-1")
17
.Select(kvp =>
18
$"{WebUtility.UrlEncode(kvp.Key)}=
19 {WebUtility.UrlEncode(kvp.Value)}"));
Request.HttpContext.Response.Redirect(url);
Note that, the call back scheme above represents a scheme we will
define in our mobile app we will name it: “xamarinapp”
You might have noticed that the user’s picture is not passed to our
5 of 10 11/28/2020, 4:08 PM
JWT Social auth with ASP.net core and Xamarin Essentials - Cool Coders about:reader?url=https://doumer.me/jwt-social-auth-with-asp-net-core...
backend even after authentication. We can get this with the access
token returned from the social media, which we mentioned earlier,
or add appropriate claims when setting up authentication.
For Google, we will just add a little bit of configuration while setting
up the Authentication in our startup.cs
google.Scope.Add("profile");
var picture =
context.User.GetProperty("picture").GetString();
context.Identity.AddClaim(new Claim("picture",
picture));
return Task.CompletedTask;
};
For Facebook, we will use the access token to request the user’s
profil picture. Here is how we do that.
services.AddIdentityMongoDbProvider<AppUser, MongoRole>
(identityOptions =>
....
},
mongoIdentityOptions => {
mongoIdentityOptions.ConnectionString =
Configuration["IdentityDB"];
}).AddDefaultTokenProviders();
6 of 10 11/28/2020, 4:08 PM
JWT Social auth with ASP.net core and Xamarin Essentials - Cool Coders about:reader?url=https://doumer.me/jwt-social-auth-with-asp-net-core...
if (user == null)
appUser.UserName = CreateUniqueUserName($"
{appUser.FirstName} {appUser.SecondName}");
user = appUser;
2 {
5 {
issuedAt.ToUnixTimeMilliseconds().ToString(), ClaimValueTypes.Integer64
9
7 of 10 11/28/2020, 4:08 PM
JWT Social auth with ASP.net core and Xamarin Essentials - Cool Coders about:reader?url=https://doumer.me/jwt-social-auth-with-asp-net-core...
19 var expirySeconds =
(long)TimeSpan.FromSeconds(Convert.ToDouble(_configuration["JwtExpire"])).TotalSecon
20
_configuration["JwtIssuer"],
22
23 _configuration["JwtIssuer"],
24 claims,
25 expires: expires.DateTime,
26 signingCredentials: creds
);
27
return (new JwtSecurityTokenHandler().WriteToken(token), expirySeconds)
28
29 }
30
31
32
To setup JWT social auth with asp.net core and xamarin Essentials,
we will have to create a Xamarin Forms project and add Xamarin
Essentials. Then follow these steps.
8 of 10 11/28/2020, 4:08 PM
JWT Social auth with ASP.net core and Xamarin Essentials - Cool Coders about:reader?url=https://doumer.me/jwt-social-auth-with-asp-net-core...
Now that we have configured the platform projects, let’s get into the
shared project. Here, we will invoke the web authenticator API, and
let it do the job of handling redirects, calling web browser e.t.c.
First, in our view model, we have two commands. One for each
button, Signin with Facebook and Google.
var jwtTokenExpiresIn =
result.Properties["jwt_token_expires"];
Then using Shell navigation, we URL encode the user info and
9 of 10 11/28/2020, 4:08 PM
JWT Social auth with ASP.net core and Xamarin Essentials - Cool Coders about:reader?url=https://doumer.me/jwt-social-auth-with-asp-net-core...
{ "token", authToken },
{ "name", $"{result.Properties["firstName"]}
{result.Properties["secondName"]}"},
{ "picture",
HttpUtility.UrlDecode(result.Properties["picture"]) }
};
await AppShell.Current.GoToAsync(url);
Conclusion
With just a few lines of code, we made JWT social auth with
ASP.net core and Xamarin Essentials functionality in our mobile
app. There Microsoft’s MSAL library for more advanced
authentication scenarios. But for small size mobile applications, this
approach is good enough. Especially if you are willing to prototype
quickly.
References
https://devblogs.microsoft.com/xamarin/authentication-xamarin-
essentials-aspnet/?WT.mc_id=DT-MVP-5003277
https://developer.android.com/reference/android/content
/IntentFilter#addDataSchemeSpecificPart(java.lang.String,%20int)
10 of 10 11/28/2020, 4:08 PM