Create an Authorisation Attribute:
namespace S3ID.PAS3.Api.AuthAttributes { using System.Security.Claims; using System.Web.Mvc; public class ClaimsAuthorizeAttribute : AuthorizeAttribute { private string claimType; private string claimValue; public ClaimsAuthorizeAttribute(string type, string value) { this.claimType = type; this.claimValue = value; } public override void OnAuthorization(AuthorizationContext filterContext) { var user = filterContext.HttpContext.User as ClaimsPrincipal; if (user != null && user.HasClaim(this.claimType, this.claimValue)) { base.OnAuthorization(filterContext); } else { base.HandleUnauthorizedRequest(filterContext); } } } }
Add claims e.g. oAuthId.AddClaim(new Claim(“Groups”, “View”)); to the OAuthAuthorizationServerProvider:
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { var authenticationService = this.dependencyResolver.Resolve(); var result = await authenticationService.AuthenticateUser(new AuthenticateUserRequest { Password = context.Password, Username = context.UserName }); switch (result.SignInResult) { case AuthenticationResults.Success: { //issue a simple default ticket. if more info is needed, add it as claims //var claims = new List (); //claims.Add(new Claim(ClaimTypes.Name, context.UserName)); //var oAuthId = new ClaimsIdentity(claims, context.Options.AuthenticationType); var oAuthId = new ClaimsIdentity(context.Options.AuthenticationType); oAuthId.AddClaim(new Claim(ClaimTypes.Name, context.UserName)); oAuthId.AddClaim(new Claim("Groups", "View")); var data = new Dictionary { { "userName", context.UserName } }; var properties = new AuthenticationProperties(data); var ticket = new AuthenticationTicket(oAuthId, properties); //context.Validated(oAuthId); context.Validated(ticket); //context.Request.Context.Authentication.SignIn(oAuthId); break; } case AuthenticationResults.FailInvalidCredentials: case AuthenticationResults.FailInvalidUsername: case AuthenticationResults.FailInvalidPassword: context.SetError("invalid_grant", "Incorrect username or password"); break; default: context.SetError("invalid_grant", "Unexpected sign in result"); break; } }
Decorate the controllers as required:
[Route("people")] [ClaimsAuthorize("Groups", "View")] public async TaskGetGroupSummaryForPeople() { var response = await base.Service.GetGroupSummaryForPeople(); return Ok(response.Summaries); }