IdentityServer4 Creating Access Token From External Provider - asp.net-core

I am using IdentityServer4 with External Providers (Google Auth). How do I generate an Access Token based on successfully logging in with Google? I would like to inject my own claims.

If implementing external login(Google Auth) in Identity Server , after Identity server receive id token from external provider , it will decode the token and get user's claims , sign in user , then create identity server's own tokens and at last return to your client app .
If you want to add custom cliams to access token which issued by Identity Server , youc can implement IProfileService :
public class MyProfileService : IProfileService
{
public MyProfileService()
{ }
public Task GetProfileDataAsync(ProfileDataRequestContext context)
{
var claims = new List<Claim>()
{
new Claim("TestKey", "TestValue")
};
context.IssuedClaims.AddRange(claims);
return Task.CompletedTask;
}
public Task IsActiveAsync(IsActiveContext context)
{
// await base.IsActiveAsync(context);
return Task.CompletedTask;
}
}
Register in DI :
services.AddTransient<IProfileService, MyProfileService>();

Related

How to use Auth0 for full signup-signin process

I am currently having troubles using auth0.com to set up whole authentication process for my asp.net web api project (I didn't write any view part, cause I'm using it only to learn auth/authoriz).
Their quickstart guides and docs are starting from obtaining a token for your application, I don't understand what is this token, does it grants an access to whole application or what? I wrote a default implementation with creating a user as an object, then generating a token and assigning it to user, then you pass user's email and password and log. I want to do the same using auth0.com
Is there a COMPLETE step-by-step guide on using auth0.com, with the explanation on how to create a user, how to let user log in etc.?
My default implementation:
private readonly UserManager<AppUser> _userManager;
private readonly TokenService _tokenService;
public AccountController(UserManager<AppUser> userManager, TokenService tokenService)
{
_tokenService = tokenService;
_userManager = userManager;
}
[AllowAnonymous]
[HttpPost("login")]
public async Task<ActionResult<UserDTO>> Login(LoginDTO loginDTO)
{
var user = await _userManager.FindByEmailAsync(loginDTO.Email);
if (user is null) return Unauthorized();
var result = await _userManager.CheckPasswordAsync(user, loginDTO.Password);
if (result)
{
return CreateUserObject(user);
}
return Unauthorized();
}
[AllowAnonymous]
[HttpPost("register")]
public async Task<ActionResult<UserDTO>> Register(RegisterDTO registerDTO)
{
if (await _userManager.Users.AnyAsync(x => x.UserName == registerDTO.Username))
{
ModelState.AddModelError("username", "Username taken");
return ValidationProblem();
}
if (await _userManager.Users.AnyAsync(x => x.Email == registerDTO.Email))
{
ModelState.AddModelError("email", "Email taken");
return ValidationProblem();
}
var user = new AppUser
{
DisplayName = registerDTO.DisplayName,
Email = registerDTO.Email,
UserName = registerDTO.Username
};
var result = await _userManager.CreateAsync(user, registerDTO.Password);
if (result.Succeeded)
{
return CreateUserObject(user);
}
return BadRequest(result.Errors);
}
[Authorize]
[HttpGet]
public async Task<ActionResult<UserDTO>> GetCurrentUser()
{
var user = await _userManager.FindByEmailAsync(User.FindFirstValue(ClaimTypes.Email));
return CreateUserObject(user);
}
private UserDTO CreateUserObject(AppUser user)
{
return new UserDTO
{
DisplayName = user.DisplayName,
Image = null,
Token = _tokenService.CreateToken(user),
Username = user.UserName
};
}
In general, you don't need to set up a sign-in/sign-up infrastructure with Auth0. The platform provides you with the Universal Login page where users can register or log in to your application.
The result of the authentication on the Auth0 side is one or two tokens that tell you some info about the user (ID token) and optionally what the user/application is allowed to do (access token).
To learn more about these tokens and the difference between them, read this article.
In your case, since your application is an API, you don't have to deal with user authentication directly. Your API isn't meant for users but for client applications.
To manage users, you can do it through the Auth0 Dashboard. If you want to create your own dashboard to manage users, you can do it through the Auth0 Management API. This is the library to use for .NET.
You assume that a client will call your API endpoints with the proper authorization expressed by an access token.
Take a look at this article for a basic authorization check for ASP.NET Core Web APIs, and this one for a permission-based approach. The articles also show how to test your protected API.
I hope these directions may help.

How can I get id_token in identity server, before redirecting to client?

After the user successfully signed in and before redirecting him to the client site I want to store the id_token in db. Actually the id_token is available in the client side but I don't know how to get it on the login process of identity server.
I would appreciate any help.
You can create a custom ITokenService by inheriting DefaultTokenService and store Id_token after creation.
public class CustomTokenService : DefaultTokenService
{
public CustomTokenService(
IClaimsService claimsProvider,
IReferenceTokenStore referenceTokenStore,
ITokenCreationService creationService,
IHttpContextAccessor contextAccessor,
ISystemClock clock,
ILogger<DefaultTokenService> logger)
: base(claimsProvider, referenceTokenStore, creationService, contextAccessor, clock, logger)
{
}
public override async Task<string> CreateSecurityTokenAsync(Token token)
{
strign jwt = await base.CreateSecurityTokenAsync(token);
// store token
return jwt;
}
}
And also you need to register CustomTokenService
builder.Services.TryAddTransient<ITokenService, CustomTokenService>();
You can use one of the built-in events : TokenIssuedSuccessEvent :
Modify your Startup.cs :
services.AddIdentityServer(options =>
{
options.Events.RaiseSuccessEvents = true;
});
Create your custom IEventSink :
public Task PersistAsync(Event evt)
{
if (evt.Id.Equals(EventIds.TokenIssuedSuccess))
{
var _test = evt as TokenIssuedSuccessEvent;
var tokens = _test.Tokens.ToList();
}
return Task.CompletedTask;
}
Then you can find id token by checking type of each tokens .
At last register the event in Startup.cs:
services.AddScoped<IEventSink, MyEventSink>();

Implement role based access control with IdentityServer4 and .NET Core

We have an existing database, and need to implement role based access control with IdentityServer4 and .NET Core.
My question is that:
1 Does IdenityServer4 support RBAC? e.g. Is it via scope claim? How should it be implemented?
2 Can I use the existing database? Or Must I create a new database?
Any advice or code sample would be appreciated.
https://github.com/IdentityServer/IdentityServer4.Samples/tree/master/Quickstarts/7_EntityFrameworkStorage
Update
We implement Resource Owner Passowrd grant type and RBAC.
Any advice or links to code sample would be appreciated.
On Identity Server side , you can create Profile Service to make IDS4 include role claim when issuing tokens .
If example , if using ASP.NET Identity to mange users/roles , you can create profile service like :
public class MyProfileService : IProfileService
{
public MyProfileService()
{ }
public Task GetProfileDataAsync(ProfileDataRequestContext context)
{
var roleClaims = context.Subject.FindAll(JwtClaimTypes.Role);
List<string> list = context.RequestedClaimTypes.ToList();
context.IssuedClaims.AddRange(roleClaims);
return Task.CompletedTask;
}
public Task IsActiveAsync(IsActiveContext context)
{
// await base.IsActiveAsync(context);
return Task.CompletedTask;
}
}
And register in Startup.cs:
services.AddTransient<IProfileService, MyProfileService>();
On client side , you should map the role claim from your JWT Token and try below config in AddOpenIdConnect middleware :
options.ClaimActions.MapJsonKey("role", "role", "role");
options.TokenValidationParameters.RoleClaimType = "role";

Using Client Credetials as the part of Usermanager<User>

Currently i am using Password Flow with my SPA application.
Now i had to integrate Client Credentials flow with my current implementation.
var descriptor = new OpenIddictApplicationDescriptor
{
ClientId = "console",
ClientSecret = "388D45FA-B36B-4988-BA59-B187D329C207",
DisplayName = "My client application",
Permissions =
{
OpenIddictConstants.Permissions.Endpoints.Token,
OpenIddictConstants.Permissions.GrantTypes.ClientCredentials
}
I have successfully implemented the both integration on my system. When sending the request using the client_id the app is authorized and authenticated as expected.
But as i notice that when using the Password flow i as using ApplicationUser as a part of Asp.net identity from dbo.User table.
But client credentials comes from different namespace that is not linked up with the Application User.
How can i setup the client_id as the part of dbo.User. How to link the the Client Credetials with Usermanager<User>?
Why i want this implementation is because during the crud operation i have the column name CreatedBy. which is refrenced to table dbo.User and i wanted to fill up the Id from dbo.User. But in the client credetials flow do not have the User.
Getting UserId
public interface IUserResolverService
{
HttpContext HttpContext { get; }
Task<Guid> GetUserId();
}
public class UserResolverService : IUserResolverService
{
IHostingEnvironment _hostingEnv;
private readonly IHttpContextAccessor accessor;
private readonly UserManager<User> _user;
public UserResolverService(IHttpContextAccessor accessor, UserManager<User> user, IHostingEnvironment hostingEnv)
{
this._user = user;
this.accessor = accessor;
this._hostingEnv = hostingEnv;
}
public HttpContext HttpContext
{
get { return accessor.HttpContext; }
}
public async Task<Guid> GetUserId()
{
var user = await _user.GetUserAsync(accessor.HttpContext.User);
return user?.Id ?? Guid.Empty;
}
}
Can you suggest me a way for this scenario?
How can i setup the client_id as the part of dbo.User. How to link the the Client Credetials with Usermanager?
It's not possible and it doesn't make any sense, actually. The client credentials is the only OAuth 2.0 core flow that doesn't involve any user as it's been designed for service-to-service scenarios, where the client application doesn't act on behalf of a user, but directly under its own identity.
To work around your issue, you may want to either make CreatedBy nullable or use one of the claim representing the application you use in AuthorizationController, like the client identifier or the client name.

OpenIdConnect access_token size and accessing claims server side

I am trying to wrap my head around several concepts here but I don't want this question to be too broad - basically what we are trying to do is use role claims as permissions to lock down our API but I am finding that the access_token is becoming too big.
We are using OpenIddict and ASP.NET Identity 3 on the server side. We have implemented the default AspNetRoleClaims table to store our claims for each role - using them as permissions.
We lock down our API endpoints using custom policy based claims authorization as shown here:
Custom Policy Based Authorization
The main issue I am finding is that our access_token containing our claims is becoming very large. We are attempting to make the ClaimType and Value to be very small in the database to make the claims footprint smaller. We have a basic CRUD type permission scheme, so for each "module" or screen in our SPA client app, there are 4 permissions. The more modules we add to our application, the more the claims are growing in the access_token and our Authorization Bearer header is becoming very large. I am worried about this becoming not very scalable as the app grows.
So the claims are embedded in the access_token and when I hit my endpoint that is locked down with a custom Policy like this...
[Authorize(Policy="MyModuleCanRead")]
[HttpGet]
public IEnumerable<MyViewModel> Get()
I can then access my ASP.NET Identity User and User.Claims in the AuthorizationHandler.
Sorry in advance if this is an obvious question - but I am wondering - in order to get the Custom Policy Based Authorization to work - does it absolutely require the claims to be in either the id_token or the access_token in order to call the handler?
If I remove the claims from the access_token, then my AuthorizationHandler code does not get hit and I cannot access my endpoint that is locked down with my custom Policy.
I am wondering if it is possible to use a custom claims policy but have the actual code that checks for the Claims inside the Authorization handler, so that the claims are not passed with each HTTP request, but are fetched server side from the Authorization cookie or from the database.
* UPDATE *
Pintpoint's answer using Authorization handlers along with the comment on how to remove additional role claims from the cookie achieved just what I was looking for.
In case this helps anyone else - here is the code to override the UserClaimsPrincipalFactory and prevent the role claims from being written to the cookie. (I had many role claims as permissions and the cookie(s) and request headers were becoming too large)
public class AppClaimsPrincipalFactory : UserClaimsPrincipalFactory<ApplicationUser, IdentityRole>
{
public AppClaimsPrincipalFactory(UserManager<ApplicationUser> userManager, RoleManager<IdentityRole> roleManager, IOptions<IdentityOptions> optionsAccessor) : base(userManager, roleManager, optionsAccessor)
{
}
public override async Task<ClaimsPrincipal> CreateAsync(ApplicationUser user)
{
if (user == null)
{
throw new ArgumentNullException(nameof(user));
}
var userId = await UserManager.GetUserIdAsync(user);
var userName = await UserManager.GetUserNameAsync(user);
var id = new ClaimsIdentity(Options.Cookies.ApplicationCookieAuthenticationScheme,
Options.ClaimsIdentity.UserNameClaimType,
Options.ClaimsIdentity.RoleClaimType);
id.AddClaim(new Claim(Options.ClaimsIdentity.UserIdClaimType, userId));
id.AddClaim(new Claim(Options.ClaimsIdentity.UserNameClaimType, userName));
if (UserManager.SupportsUserSecurityStamp)
{
id.AddClaim(new Claim(Options.ClaimsIdentity.SecurityStampClaimType,
await UserManager.GetSecurityStampAsync(user)));
}
// code removed that adds the role claims
if (UserManager.SupportsUserClaim)
{
id.AddClaims(await UserManager.GetClaimsAsync(user));
}
return new ClaimsPrincipal(id);
}
}
I am wondering if it is possible to use a custom claims policy but have the actual code that checks for the Claims inside the Authorization handler, so that the claims are not passed with each HTTP request, but are fetched server side from the Authorization cookie or from the database.
It's definitely possible. Here's how you could do that:
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped<IAuthorizationHandler, PermissionAuthorizationHandler>();
services.AddAuthorization(options =>
{
options.AddPolicy("Has-Edit-User-Profiles-Permission", builder =>
{
builder.RequirePermission("Edit-User-Profiles");
});
});
}
}
public class PermissionAuthorizationRequirement : IAuthorizationRequirement
{
public PermissionAuthorizationRequirement(string permission)
{
if (string.IsNullOrEmpty(permission))
{
throw new ArgumentException("The permission cannot be null or empty.", nameof(permission));
}
Permission = permission;
}
public string Permission { get; set; }
}
public class PermissionAuthorizationHandler :
AuthorizationHandler<PermissionAuthorizationRequirement>
{
private readonly UserManager<ApplicationUser> _userManager;
public PermissionAuthorizationHandler(UserManager<ApplicationUser> userManager)
{
if (userManager == null)
{
throw new ArgumentNullException(nameof(userManager));
}
_userManager = userManager;
}
protected override async Task HandleRequirementAsync(
AuthorizationHandlerContext context,
PermissionAuthorizationRequirement requirement)
{
if (context.User == null)
{
return;
}
var user = await _userManager.GetUserAsync(context.User);
if (user == null)
{
return;
}
// Use whatever API you need to ensure the user has the requested permission.
if (await _userManager.IsInRoleAsync(user, requirement.Permission))
{
context.Succeed(requirement);
}
}
}
public static class PermissionAuthorizationExtensions
{
public static AuthorizationPolicyBuilder RequirePermission(
this AuthorizationPolicyBuilder builder, string permission)
{
if (builder == null)
{
throw new ArgumentNullException(nameof(builder));
}
if (string.IsNullOrEmpty(permission))
{
throw new ArgumentException("The permission cannot be null or empty.", nameof(permission));
}
return builder.AddRequirements(new PermissionAuthorizationRequirement(permission));
}
}