-
Notifications
You must be signed in to change notification settings - Fork 10.3k
Add MapIdentityApi<TUser>() #47414
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Add MapIdentityApi<TUser>() #47414
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
12 changes: 12 additions & 0 deletions
12
src/Identity/Core/src/DTO/IdentityEndpointsJsonSerializerContext.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,12 @@ | ||
// Licensed to the .NET Foundation under one or more agreements. | ||
// The .NET Foundation licenses this file to you under the MIT license. | ||
|
||
using System.Text.Json.Serialization; | ||
|
||
namespace Microsoft.AspNetCore.Identity.DTO; | ||
|
||
[JsonSerializable(typeof(RegisterRequest))] | ||
[JsonSerializable(typeof(LoginRequest))] | ||
internal sealed partial class IdentityEndpointsJsonSerializerContext : JsonSerializerContext | ||
{ | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
// Licensed to the .NET Foundation under one or more agreements. | ||
// The .NET Foundation licenses this file to you under the MIT license. | ||
|
||
namespace Microsoft.AspNetCore.Identity.DTO; | ||
|
||
internal sealed class LoginRequest | ||
{ | ||
public required string Username { get; init; } | ||
public required string Password { get; init; } | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
// Licensed to the .NET Foundation under one or more agreements. | ||
// The .NET Foundation licenses this file to you under the MIT license. | ||
|
||
namespace Microsoft.AspNetCore.Identity.DTO; | ||
|
||
internal sealed class RegisterRequest | ||
{ | ||
public required string Username { get; init; } | ||
public required string Password { get; init; } | ||
} |
107 changes: 107 additions & 0 deletions
107
src/Identity/Core/src/IdentityApiEndpointRouteBuilderExtensions.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,107 @@ | ||
// Licensed to the .NET Foundation under one or more agreements. | ||
// The .NET Foundation licenses this file to you under the MIT license. | ||
|
||
using System.Diagnostics.CodeAnalysis; | ||
using System.Linq; | ||
using Microsoft.AspNetCore.Authentication.BearerToken.DTO; | ||
using Microsoft.AspNetCore.Builder; | ||
using Microsoft.AspNetCore.Http; | ||
using Microsoft.AspNetCore.Http.HttpResults; | ||
using Microsoft.AspNetCore.Http.Metadata; | ||
using Microsoft.AspNetCore.Identity; | ||
using Microsoft.AspNetCore.Identity.DTO; | ||
using Microsoft.Extensions.DependencyInjection; | ||
|
||
namespace Microsoft.AspNetCore.Routing; | ||
|
||
/// <summary> | ||
/// Provides extension methods for <see cref="IEndpointRouteBuilder"/> to add identity endpoints. | ||
/// </summary> | ||
public static class IdentityApiEndpointRouteBuilderExtensions | ||
{ | ||
/// <summary> | ||
/// Add endpoints for registering, logging in, and logging out using ASP.NET Core Identity. | ||
/// </summary> | ||
/// <typeparam name="TUser">The type describing the user. This should match the generic parameter in <see cref="UserManager{TUser}"/>.</typeparam> | ||
/// <param name="endpoints"> | ||
/// The <see cref="IEndpointRouteBuilder"/> to add the identity endpoints to. | ||
/// Call <see cref="EndpointRouteBuilderExtensions.MapGroup(IEndpointRouteBuilder, string)"/> to add a prefix to all the endpoints. | ||
/// </param> | ||
/// <returns>An <see cref="IEndpointConventionBuilder"/> to further customize the added endpoints.</returns> | ||
// TODO: Remove RequiresDynamicCode when https://github.com/dotnet/aspnetcore/issues/47918 is fixed and RDG is enabled. | ||
[RequiresDynamicCode("This API requires generated code that is not compatible with native AOT applications.")] | ||
public static IEndpointConventionBuilder MapIdentityApi<TUser>(this IEndpointRouteBuilder endpoints) where TUser : class, new() | ||
{ | ||
ArgumentNullException.ThrowIfNull(endpoints); | ||
|
||
var routeGroup = endpoints.MapGroup(""); | ||
|
||
// NOTE: We cannot inject UserManager<TUser> directly because the TUser generic parameter is currently unsupported by RDG. | ||
// https://github.com/dotnet/aspnetcore/issues/47338 | ||
routeGroup.MapPost("/register", async Task<Results<Ok, ValidationProblem>> | ||
([FromBody] RegisterRequest registration, [FromServices] IServiceProvider services) => | ||
{ | ||
var userManager = services.GetRequiredService<UserManager<TUser>>(); | ||
|
||
var user = new TUser(); | ||
await userManager.SetUserNameAsync(user, registration.Username); | ||
var result = await userManager.CreateAsync(user, registration.Password); | ||
|
||
if (result.Succeeded) | ||
{ | ||
return TypedResults.Ok(); | ||
} | ||
|
||
return TypedResults.ValidationProblem(result.Errors.ToDictionary(e => e.Code, e => new[] { e.Description })); | ||
}); | ||
|
||
routeGroup.MapPost("/login", async Task<Results<UnauthorizedHttpResult, Ok<AccessTokenResponse>, SignInHttpResult>> | ||
([FromBody] LoginRequest login, [FromQuery] bool? cookieMode, [FromServices] IServiceProvider services) => | ||
{ | ||
var userManager = services.GetRequiredService<UserManager<TUser>>(); | ||
var user = await userManager.FindByNameAsync(login.Username); | ||
|
||
if (user is null || !await userManager.CheckPasswordAsync(user, login.Password)) | ||
{ | ||
return TypedResults.Unauthorized(); | ||
} | ||
|
||
var claimsFactory = services.GetRequiredService<IUserClaimsPrincipalFactory<TUser>>(); | ||
var claimsPrincipal = await claimsFactory.CreateAsync(user); | ||
|
||
var useCookies = cookieMode ?? false; | ||
var scheme = useCookies ? IdentityConstants.ApplicationScheme : IdentityConstants.BearerScheme; | ||
|
||
return TypedResults.SignIn(claimsPrincipal, authenticationScheme: scheme); | ||
}); | ||
|
||
return new IdentityEndpointsConventionBuilder(routeGroup); | ||
} | ||
|
||
// Wrap RouteGroupBuilder with a non-public type to avoid a potential future behavioral breaking change. | ||
private sealed class IdentityEndpointsConventionBuilder(RouteGroupBuilder inner) : IEndpointConventionBuilder | ||
{ | ||
#pragma warning disable CA1822 // Mark members as static False positive reported by https://github.com/dotnet/roslyn-analyzers/issues/6573 | ||
private IEndpointConventionBuilder InnerAsConventionBuilder => inner; | ||
#pragma warning restore CA1822 // Mark members as static | ||
|
||
public void Add(Action<EndpointBuilder> convention) => InnerAsConventionBuilder.Add(convention); | ||
public void Finally(Action<EndpointBuilder> finallyConvention) => InnerAsConventionBuilder.Finally(finallyConvention); | ||
} | ||
|
||
[AttributeUsage(AttributeTargets.Parameter)] | ||
private sealed class FromBodyAttribute : Attribute, IFromBodyMetadata | ||
{ | ||
} | ||
|
||
[AttributeUsage(AttributeTargets.Parameter)] | ||
private sealed class FromServicesAttribute : Attribute, IFromServiceMetadata | ||
{ | ||
} | ||
|
||
[AttributeUsage(AttributeTargets.Parameter)] | ||
private sealed class FromQueryAttribute : Attribute, IFromQueryMetadata | ||
{ | ||
public string? Name => null; | ||
} | ||
} |
34 changes: 34 additions & 0 deletions
34
src/Identity/Core/src/IdentityApiEndpointsIdentityBuilderExtensions.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
// Licensed to the .NET Foundation under one or more agreements. | ||
// The .NET Foundation licenses this file to you under the MIT license. | ||
|
||
using Microsoft.AspNetCore.Authentication; | ||
using Microsoft.AspNetCore.Authentication.BearerToken; | ||
using Microsoft.AspNetCore.Http.Json; | ||
using Microsoft.AspNetCore.Routing; | ||
using Microsoft.Extensions.DependencyInjection; | ||
using Microsoft.Extensions.DependencyInjection.Extensions; | ||
using Microsoft.Extensions.Options; | ||
|
||
namespace Microsoft.AspNetCore.Identity; | ||
|
||
/// <summary> | ||
/// <see cref="IdentityBuilder"/> extension methods to support <see cref="IdentityApiEndpointRouteBuilderExtensions.MapIdentityApi{TUser}(IEndpointRouteBuilder)"/>. | ||
/// </summary> | ||
public static class IdentityApiEndpointsIdentityBuilderExtensions | ||
{ | ||
/// <summary> | ||
/// Adds configuration ans services needed to support <see cref="IdentityApiEndpointRouteBuilderExtensions.MapIdentityApi{TUser}(IEndpointRouteBuilder)"/> | ||
/// but does not configure authentication. Call <see cref="BearerTokenExtensions.AddBearerToken(AuthenticationBuilder, Action{BearerTokenOptions}?)"/> and/or | ||
/// <see cref="IdentityCookieAuthenticationBuilderExtensions.AddIdentityCookies(AuthenticationBuilder)"/> to configure authentication separately. | ||
/// </summary> | ||
/// <param name="builder">The <see cref="IdentityBuilder"/>.</param> | ||
/// <returns>The <see cref="IdentityBuilder"/>.</returns> | ||
public static IdentityBuilder AddApiEndpoints(this IdentityBuilder builder) | ||
{ | ||
ArgumentNullException.ThrowIfNull(builder); | ||
|
||
builder.AddSignInManager(); | ||
builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton<IConfigureOptions<JsonOptions>, IdentityEndpointsJsonOptionsSetup>()); | ||
return builder; | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
ans => and