Angular 2 SPA Web API - Explanation
Configuring the ASP.NET Core Web API & IdentityServer4
Let's see what the Config.cs file contains for configuring IdentityServer4. The following is the identification of our client app:
// Clients want to access resources.
public static IEnumerable<Client> GetClients()
{
// Clients credentials.
return new List<Client>
{
// http://docs.identityserver.io/en/dev/reference/client.html.
new Client
{
ClientId = "Angular2SPA",
AllowedGrantTypes = GrantTypes.ResourceOwnerPassword, // Resource Owner Password Credential grant.
AllowAccessTokensViaBrowser = true,
RequireClientSecret = false, // This client does not need a secret to request tokens from the token endpoint.
AccessTokenLifetime = 900, // Lifetime of access token in seconds.
AllowedScopes = {
IdentityServerConstants.StandardScopes.OpenId, // For UserInfo endpoint.
IdentityServerConstants.StandardScopes.Profile,
"WebAPI",
"roles"
},
AllowOfflineAccess = true // For refresh token.
}
};
}
As you can see, you can add other clients with their own configuration. Our Angular 2 app, identified as Angular2SPA:
- uses ROPC;
- doesn't use a secret key: in a client application it would be useless because visible;
- has an access token for 15 minutes, then need to refresh the token;
- can access to the scopes: in this case our Web API, called with a lot of imagination WebAPI, the OfflineAccess for refresh token and OpenId to access to the user's info.
// Identity resources (used by UserInfo endpoint).
public static IEnumerable<IdentityResource> GetIdentityResources()
{
return new List<IdentityResource>
{
new IdentityResources.OpenId(),
new IdentityResources.Profile(),
new IdentityResource("roles", new List<string> { "role" })
};
}
// Api resources.
public static IEnumerable<ApiResource> GetApiResources()
{
return new List<ApiResource>
{
new ApiResource("WebAPI" ) {
UserClaims = { "role" }
}
};
}
Note that we can define which user claims will be included in the access token.
Because our Web API is in the same project, in Configure method of Startup.cs file, we add the authentication middleware:
// IdentityServer4.AccessTokenValidation: authentication middleware for the API.
app.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions
{
Authority = "http://localhost:5000/",
AllowedScopes = { "WebAPI" },
RequireHttpsMetadata = false
});
We complete the configuration by adding IdentityServer in ConfigureServices method:
// Adds IdentityServer.
// The AddTemporarySigningCredential extension creates temporary key material for signing tokens on every start.
// Again this might be useful to get started, but needs to be replaced by some persistent key material for production scenarios.
// See the cryptography docs for more information: http://docs.identityserver.io/en/release/topics/crypto.html#refcrypto
services.AddIdentityServer()
.AddTemporarySigningCredential()
.AddInMemoryIdentityResources(Config.GetIdentityResources())
.AddInMemoryApiResources(Config.GetApiResources())
.AddInMemoryClients(Config.GetClients())
.AddAspNetIdentity<ApplicationUser>(); // IdentityServer4.AspNetIdentity.
The extension method AddAspNetIdentity to use the ASP.NET Identity requires another setting:
// Adds IdentityServer.
app.UseIdentityServer();
Now we can add related services: Identity and for simplicity SQLite.
// Identity & SQLite.
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlite(Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
and
// Adds Identity.
app.UseIdentity();
Also we define the policy of access to the Web Api controllers. In our sample, we create two policies:
- Manage Account only for administrator role;
- Access Resources for administrator role and for user role.
// Claims-Based Authorization: role claims.
services.AddAuthorization(options =>
{
// Policy for dashboard: only administrator role.
options.AddPolicy("Manage Accounts", policy => policy.RequireClaim("role", "administrator"));
// Policy for resources: user or administrator role.
options.AddPolicy("Access Resources", policyBuilder => policyBuilder.RequireAssertion(
context => context.User.HasClaim(claim => (claim.Type == "role" && claim.Value == "user")
|| (claim.Type == "role" && claim.Value == "administrator"))
)
);
});
We add the authorization to the Identity controller, which is used by the dashboard:
[Route("api/[controller]")]
[Authorize(Policy = "Manage Accounts")] // Authorization policy for this API.
public class IdentityController : Controller
...
and to Values controller, that returns the resources for the authenticated users:
[Route("api/[controller]")]
[Authorize(Policy = "Access Resources")] // Authorization policy for this API.
public class ValuesController : Controller
...
Remember: when we have defined our APIResource, we have included the roles with user claim role to allow the user to access the resources.
Finally, we set the startup on the entry point of the client application:
// Microsoft.AspNetCore.StaticFiles: API for starting the application from wwwroot.
// Uses default files as index.html.
app.UseDefaultFiles();
// Uses static file for the current path.
app.UseStaticFiles();
Understanding how it works
It's important to understand and observe how the authentication and authorization services work, in order to implement the client app.
If you debug the app and navigate the browers to:
http://localhost:5000/.well-known/openid-configuration
you should see the so-called discovery document.
The discovery endpoint can be used to retrieve metadata about IdentityServer.
For an authentication, we need to send the request at the token_endpoint:
http://localhost:5000/connect/token
For example, you can use Postman as client to send this POST request:
POST /connect/token HTTP/1.1
Host: localhost:5000
Content-Type: application/x-www-form-urlencoded
client_id=Angular2SPA&grant_type=password&username=admin%40gmail.com&password=Admin01*&scope=WebAPI+offline_access+openid+profile+roles
Note the Content-Type as x-www-form-urlencoded, and parameters provided in the body. This is the response:
{
"access_token": "eyJhbGci...",
"expires_in": 900,
"token_type": "Bearer",
"refresh_token": "5007bc4b..."
}
The user has been authenticated, and he has an access token that will expire in 900 seconds, but he has also a refresh token. You can use a tool like JSON Web Token to decode the JWT and see the payload (with our scope claims):
{
"nbf": 1480712377,
"exp": 1480713277,
"iss": "http://localhost:5000",
"aud": "http://localhost:5000/resources",
"client_id": "Angular2SPA",
"sub": "c0bb2220-8c99-46dc-ad39-b707f37f047f",
"auth_time": 1480712377,
"idp": "local",
"role": "administrator",
"scope": [
"offline_access",
"openid",
"profile",
"roles",
"WebAPI"
],
"amr": [
"pwd"
]
}
Now we can send a GET request to our Web API in this way:
GET /api/values HTTP/1.1
Host: localhost:5000
Authorization: Bearer eyJhbGci...
This request contains a header parameter named Authorization and its value is the bearer token. The response:
[
"value1",
"value2"
]
And when, past the 15 minutes, the token expires? The user can no longer access resources.
You can ask him to sign in again, or handle a refresh token strategy: to get a new access token,
you can send a POST request, with grant_type set to refresh_token and refresh token as parameters:
POST /connect/token HTTP/1.1
Host: localhost:5000
Content-Type: application/x-www-form-urlencoded
client_id=Angular2SPA&grant_type=refresh_token&refresh_token=5007bc4b...
Implementing the Angular 2 SPA
Ok, how do we transform the requests done via Postman in an Angular 2 app?
In this sample, to send unauthenticated requests for signing in and signing up the user, we use the Angular 2 http module, as in AuthenticationService class:
/**
* Tries to sign in the user.
*
* @param username
* @param password
* @return The user's data
*/
public signin(username: string, password: string): Observable<any> {
// Token endpoint & params.
let tokenEndpoint: string = Config.TOKEN_ENDPOINT;
let params: any = {
client_id: Config.CLIENT_ID,
grant_type: Config.GRANT_TYPE,
username: username,
password: password,
scope: Config.SCOPE
};
// Encodes the parameters.
let body: string = this.encodeParams(params);
this.authTime = new Date().valueOf();
return this.http.post(tokenEndpoint, body, this.options)
.map((res: Response) => {
let body: any = res.json();
// Sign in successful if there's an access token in the response.
if (typeof body.access_token !== 'undefined') {
// Stores access token & refresh token.
this.store(body);
// Gets user info.
this.userInfo();
// Tells all the subscribers about the new status.
this.signinSubject.next(true);
}
}).catch((error: any) => {
// Error on post request.
return Observable.throw(error);
});
}
We send a request to UserInfo endpoint to get the user's data using angular2-jwt library, that builds for us the header with the authorization token:
/**
* Calls UserInfo endpoint to retrieve user's data.
*/
private userInfo(): void {
if (this.tokenNotExpired()) {
this.authHttp.get(Config.USERINFO_ENDPOINT)
.subscribe(
(res: any) => {
let user: any = res.json();
let roles: string[] = user.role;
// Tells all the subscribers about the new data & roles.
this.userSubject.next(user);
this.rolesSubject.next(user.role);
},
(error: any) => {
// Need to handle this error.
console.log(error);
});
}
}
In this example, we use a scheduler to request a new access token before it expires through the refresh token:
/**
* Optional strategy for refresh token through a scheduler.
*
* Will schedule a refresh at the appropriate time.
*/
public scheduleRefresh(): void {
let source = this.authHttp.tokenStream.flatMap(
(token: string) => {
let delay: number = this.expiresIn - this.offsetSeconds * 1000;
return Observable.interval(delay);
});
this.refreshSubscription = source.subscribe(() => {
this.getNewToken().subscribe(
() => {
// Scheduler works.
},
(error: any) => {
// Need to handle this error.
console.log(error);
}
);
});
}
/**
* Case when the user comes back to the app after closing it.
*/
public startupTokenRefresh(): void {
// If the user is authenticated, uses the token stream
// provided by angular2-jwt and flatMap the token.
if (this.signinSubject.getValue()) {
let source = this.authHttp.tokenStream.flatMap(
(token: string) => {
let now: number = new Date().valueOf();
let exp: number = Helpers.getExp();
let delay: number = exp - now - this.offsetSeconds * 1000;
// Uses the delay in a timer to run the refresh at the proper time.
return Observable.timer(delay);
});
// Once the delay time from above is reached, gets a new JWT and schedules additional refreshes.
source.subscribe(() => {
this.getNewToken().subscribe(
() => {
this.scheduleRefresh();
},
(error: any) => {
// Need to handle this error.
console.log(error);
}
);
});
}
}
/**
* Unsubscribes from the scheduling of the refresh token.
*/
public unscheduleRefresh(): void {
if (this.refreshSubscription) {
this.refreshSubscription.unsubscribe();
}
}
/**
* Tries to get a new token using refresh token.
*/
public getNewToken(): Observable<any> {
let refreshToken: string = Helpers.getToken('refresh_token');
// Token endpoint & params.
let tokenEndpoint: string = Config.TOKEN_ENDPOINT;
let params: any = {
client_id: Config.CLIENT_ID,
grant_type: "refresh_token",
refresh_token: refreshToken
};
// Encodes the parameters.
let body: string = this.encodeParams(params);
this.authTime = new Date().valueOf();
return this.http.post(tokenEndpoint, body, this.options)
.map((res: Response) => {
let body: any = res.json();
// Successful if there's an access token in the response.
if (typeof body.access_token !== 'undefined') {
// Stores access token & refresh token.
this.store(body);
}
}).catch((error: any) => {
// Error on post request.
return Observable.throw(error);
});
}
To send authenticated requests, as in ResourcesComponent class, we still use angular2-jwt library:
// Sends an authenticated request.
this.authHttp.get("/api/values")
.subscribe(
(res: any) => {
this.values = res.json();
},
(error: any) => {
console.log(error);
});
Building the Angular 2 app with AoT compilation & webpack
For production, we build the Angular 2 app through ngc compiler & webpack. To do this, after the AoT compilation, in webpack.config.js file we set as entry point main-aot.ts:
// In production mode, we use AoT compilation & minification.
module.exports = {
entry: {
'app-aot': './app/main-aot.js'
},
...
and as output the wwwroot folder (as set in Startup.cs):
output: {
path: "./wwwroot/",
filename: "dist/[name].bundle.js",
chunkFilename: 'dist/[name].chunk.js'
},
Finally, we ask webpack to insert the script of the bundle in our index.html:
// Adds script for the bundle in index.html.
new HtmlWebpackPlugin({
filename: 'index.html',
inject: 'body',
template: 'app/index.html'
})
in this example it it possible to get roles from the user claims. is it possible to get the roles from asp.net identity roles?
Hi @nadavten,
this is an interesting question. To work with the tokens, you need to use the claims. In this example, I chose for simplicity to create roles as claims directly, but you can use the roles of the membership system of Identity transforming them into claims, using Role Claims.
The method roleManager.AddClaimAsync creates a claim for the role, and adds it to AspNetRoleClaims table, so that it becomes an user's claim and it's automatically included in the token.
The following is an interesting article about Role Claims: http://benfoster.io/blog/asp-net-identity-role-claims
For example, the DbInitializer class of this project could be changed in this way:
...
// Roles.
var adminRole = new IdentityRole("administrator");
var roleStore = new RoleStore<IdentityRole>(context);
await roleStore.CreateAsync(adminRole);
// Adds Role Claim.
await roleStore.AddClaimAsync(adminRole, new Claim(JwtClaimTypes.Role, "administrator"));
var userRole = new IdentityUserRole<string>
{
RoleId = adminRole.Id,
};
user.Roles.Add(userRole);
// Claims.
var claims = new IdentityUserClaim<string>[] {
new IdentityUserClaim<string> { ClaimType = JwtClaimTypes.GivenName, ClaimValue = user.GivenName },
new IdentityUserClaim<string> { ClaimType = JwtClaimTypes.FamilyName, ClaimValue = user.FamilyName }
};
foreach (var claim in claims)
{
user.Claims.Add(claim);
}
var userStore = new UserStore<ApplicationUser>(context);
await userStore.CreateAsync(user);
...
It remains unchanged, however, the use of the Claims-Based Authorization.
If you are still interested, I added Role Claims to the back-end to manage Identity roles.
I'm closing this issue. If you need, open a new issue. Greetings
I did some research and experts are saying resource owner password is a big no no for SPA application. They recommend implicit flow. But the biggest annoying thing is the login form is separated from your app.. I have a requirement where login form should not be separated so i'm extremely lost now. cant follow best practices because of the requirement.
@darkj3an It's true: the recommended way is implicit flow.
The resource owner password credentials grant type is suitable in cases where the resource owner has a trust relationship with the client, such as the device operating system or a highly privileged application. The authorization server should take special care when enabling this grant type and only allow it when other flows are not viable.
https://tools.ietf.org/html/rfc6749#section-4.3
I think the only way is to evaluate if the level of security is more important than the graphic aspect, depending on the type of application being built.