asp.net-identity,asp.net-web-api2,claims-based-identity,asp.net-identity-2,asp.net-authentication , ASP.NET Identity “Role-based” Claims


ASP.NET Identity “Role-based” Claims

Question:

Tag: asp.net-identity,asp.net-web-api2,claims-based-identity,asp.net-identity-2,asp.net-authentication

I understand that I can use claims to make statements about a user:

var claims = new List<Claim>();
claims.Add(new Claim(ClaimTypes.Name, "Peter"));
claims.Add(new Claim(ClaimTypes.Email, "[email protected]"));

But how should I store "role-based" claims? For example:

The user is a super administrator.

claims.Add(new Claim("IsSuperAdmin, "true"));

The value parameter "true" feels completely redundant. How else can this statement be expressed using claims?


Answer:

This is already done for you by the framework. When user is logged in, all user roles are added as claims with claims type being ClaimTypes.Role and values are role name.

And when you execute IPrincipal.IsInRole("SuperAdmin") the framework actually checks if the claim with type ClaimTypes.Role and value SuperAdmin is present on the user.

So don't need to do anything special. Just add a user to a role.


Related:


How to get .net web api in jsonP, although it returns json data by default


asp.net-mvc,asp.net-mvc-4,asp.net-web-api,asp.net-mvc-5,asp.net-web-api2
I am working on .net web api in Asp.net Mvc5 project... By default it returns xml or json...in my project json/xml data returning fine... I am looking for the setting so that i can get response in JSONP.... Web Api config : public static void Register(HttpConfiguration config) { // Web...

Onion Architecture Identity Framework


asp.net,.net,asp.net-web-api,asp.net-identity,onion-architecture
I am following Onion Architecture. And in that I am using ASP.NET Identity Framework. Here is my Project Structure: 1-Core - Domain Classes //It contains my T4 template classes -- AppUser //It is Identity User. - Repository Interfaces - Service Interfaces 2-Infrastructure - Data //It contains my edmx file, I...

Web API 2 requires trailing slash for custom attribute routing to work


asp.net-mvc,rest,asp.net-web-api2
I have created a Web API 2 project and although the APIs work fine, I must enter a trailing slash for them to do so. This results in a 404 http://www.myURL.com/api/v1/get/addressfromlatlong/UK/50.9742794/-0.1146699 This shows the JSON response as intended http://www.myURL.com/api/v1/get/addressfromlatlong/UK/50.9742794/-0.1146699/ I have another controller with a custom action that works fine....

How to send email to registered user (MVC)


asp.net-mvc,email,asp.net-identity
My problem is this one, I have users that are registered in a basic MVC 5 application, when they register they provide email address and a username. In the application userA can see what userB created (ie a product or whatever), what I want to do is that for userA...

Leverage MultipleApiVersions in Swagger with attribute versioning


attributes,asp.net-web-api2,swagger,swagger-ui,swashbuckle
Is it possible to leverage MultipleApiVersions in Swagger UI / Swashbuckle when using attribute routing? Specifically, I implemented versioning by: using System.Web.Http; namespace RESTServices.Controllers.v1 { [Route("api/v1/Test")] public class TestV1Controller : ApiController { ... } Version 2 would be in a v2 namespace. In a controller named TestV2Controller. The route would...

web api Bad Request when getting access token after moving to production


c#,asp.net,asp.net-web-api2
I have a web api that is working great in test using an access token / bearer authentication. I authenticate and make requests using HttpClient. Easy. Here is the basic web client setup. The base address is a constant that I change when moving to production. public static HttpClient GetClient()...

WebApi Routing not working for Post


routing,asp.net-web-api2,asp.net-web-api-routing
My WebApiConfig has following routes // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { controller = "Employee", action = "Get", id = RouteParameter.Optional } ); The Post WebApi method has got following Signatures [HttpPost] public IHttpActionResult Post(Employee emp) { ..... } When i try to call...

Asp .NET Identity Cookie Authentication


authentication,asp.net-identity
I'm using MVC 5 default template with "Individual Accounts" selected for authentication. it uses ASP .NET Identity with Entity Framework. Using Chrome I opened the app and Registered a user and then login with the user. I accidentally deleted the database. Now when I open the app again in Chrome...

XSS in angularjs app and web api 2


angularjs,xss,asp.net-web-api2,antixsslibrary
I have a web application. I am using Angularjs and Web Api2. I have a simple form where user can insert some free text that will be send via email to other people. The text is also saved on db and later can be shown in a web site page....

Simple.OData.Client - Unable to invoke Action that accepts entity collection parameter


odata,asp.net-web-api2,simple.odata
I get error "The parameter 'wheels' is of Edm type kind 'Collection'. You cannot call CreateCollectionWriter on a parameter that is not of Edm type kind 'Collection'." Below are details of my setup: Web API 2.2 OData v4 service : I have defined Action in WheelsController class in my...

Using A Service DB Context as WebApi OData Context


c#,wcf,odata,asp.net-web-api2
I'm trying create a OData service using Webapi 2. I've already created a working example that works with a local context. Now, I want to use a Context Provided from a seperate WCF Service. WebApiConfig.cs: public static void Register(HttpConfiguration config) { config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id...

OData Annotations do not appear when not localhost


odata,asp.net-web-api2
I'm building an OData response by throwing a standard HttpResponseException. The exception itself is built with an HttpResponseMessage based on ODataError. new ODataError() { ErrorCode = code, Message = message, InnerError = new ODataInnerError() { Message = innerException.Message, StackTrace = innerException.StackTrace, TypeName = innerException.GetType().Name }, InstanceAnnotations = annotations }); The...

Asp.Net Identity find users not in role


asp.net,linq,entity-framework,asp.net-identity
I need to find all users that DONT'T contain a certain role, using Asp.Net Identity. So far I have something like this but it is not working. (From role In context.Roles From userRoles In role.Users Join us In context.Users On us.Id Equals userRoles.UserId Where role.Name <> "SomeRole" Select us.UserName) This...

Identity Framework create a new password for a user (without a password)


c#,asp.net-web-api,asp.net-identity
So, I have this site where users can only be created by administrators. I set up my Web API method like this: /// <summary> /// Creates a user (with password) /// </summary> /// <param name="model">The bound user model</param> /// <returns></returns> [HttpPost] [Route("")] public async Task<IHttpActionResult> CreateUser(UserBindingModel model) { // If...

File upload web api 2.0 error after deployment on IIS 8.5


c#,iis,file-upload,asp.net-web-api2
The below code works very well on development environment VS 2012, the images are saved to App_Data. When I deployed the same on Win 8.1, IIS 8.5, the App_Data was missing. I manually create the folder and set the properties as given in http://hintdesk.com/tutorial-publish-asp-net-web-api-in-iis-8-5-and-windows-8-1/. I am seeing strange behavior as...

No type was found that matches the controller name


asp.net,asp.net-web-api2
I've got the infamous Web Api No type was found that matches the controller name. I had this web service working until we did a little restructuring of the file system and classes and now I'm getting this error. The File system sits as default with the Controllers and Models...

How do I plug a custom roles manager into the AuthorizeAttribute?


asp.net-mvc,asp.net-identity
I have an older database schema that I cannot change. It has a single user table with an integer field to designate user level where 1 is standard user and 5 is administrator. I'm writing an MVC front end and I want to use ASP.NET Identity. I've figured out everything...

AuthenticationManager.GetExternalLoginInfoAsync() always null


c#,asp.net-identity,asp.net-identity-2
ExternalLoginInfo loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync(); Why must this line always return null? It happens when the user tries to login using ANY provider. I know the FLOW is correct because actually it works locally, but when I deploy the website it always returns null. From what I understand it's using...

How to send a custom object from OnException method?


c#,asp.net,asp.net-mvc,asp.net-web-api2
public override void OnException( System.Web.Http.Filters.HttpActionExecutedContext actionExecutedContext) { if (actionExecutedContext.Exception != null) Elmah.ErrorSignal.FromCurrentContext().Raise(actionExecutedContext.Exception); base.OnException(actionExecutedContext); throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError) { Content = new StringContent(actionExecutedContext.Exception.Message), ReasonPhrase = "Deadly Exception", }); } This is my filter for Model passed to any asp.net web api. It...

Thinktecture multiple website connect ( SSO )


asp.net-mvc,asp.net-identity,thinktecture-ident-server
I just started exploring Thinktecture becuase i have multiple websites and i want Single Sign On between them . So , i started working on this and i am following this tutorial Thinktecture tutorial Every thing works fine following this tutorial , when i added another application in my same...

Where does EntityFramework get the connection string to my local database?


c#,entity-framework,asp.net-identity
I have created a web form that is a registration form using Identity. The form calls code behind that looks like this: protected void CreateUser_Click(object sender, EventArgs e) { var userStore = new UserStore<IdentityUser>(); var manager = new UserManager<IdentityUser>(userStore); var user = new IdentityUser() { UserName = UserName.Text }; IdentityResult...

Entity Framework throws Invalid object name


c#,sql-server,entity-framework,ado.net,asp.net-web-api2
I have a DB in SQL Server with several tables. I have created a Class Library project in VS2013. Created a DBContext, added the database as a ADO.NET file and created a repository for running the queries. I have created a Web API2 empty project with a controller for creating...

Web Api and where should I contorol Request Header data


asp.net-web-api,asp.net-web-api2
In Asp.net Web Api, I want to control, request "access token" key is (which is in request header) valid or not. But I cound't decide where should I implement this kind of control. ActionFilter or controller constructor etc. etc.

Configure the authorization server endpoint


c#,asp.net,oauth,asp.net-identity,asp.net-5
Question How do we use a bearer token with ASP.NET 5 using a username and password flow? For our scenario, we want to let a user register and login using AJAX calls without needing to use an external login. To do this, we need to have an authorization server endpoint....

Losing HttpContext with async await in ASP.NET Identity GetRolesAsync


c#,asp.net-web-api,async-await,asp.net-identity
This is more of an async/await question than ASP.NET Identity. I am using Asp.Net Identity, and have a custom UserStore, with a customized GetRolesAsync method. The UserManager is called from a WebApi controller. public class MyWebApiController { private MyUserManager manager = new MyUserManager(new MyUserStore()); [HttpGet] public async Task<bool> MyWebApiMethod(int x)...

Best practices when configuring relying party for on-premise authorization


active-directory,asp.net-identity
I've created a website within the company that utilizes our active directory server to authenticate. I am concerned about security surrounding setting up relying parties with "localhost" domains. I've pretty much followed this guide on setup. You'll notice about halfway down the page, there is a step to set up...

Implementing UserManager to use a custom class and Stored Procedures


.net,asp.net-mvc,asp.net-identity,asp.net-identity-2
All of the authentication and authorization process of my app is done using stored procedures. I've written a class with all of functionalities that I need, e.g. GetUsers, Login, AddRole, AddMember, etc. Also the admin page for managing users and roles and permissions is done by using this class. I...

WebApi Serving Videos on Mobile Devices


ios,html5-video,mobile-safari,asp.net-web-api2
I'm using WebApi to serve videos on a website. I've tested this on all major desktop browsers and the HTML5 Video tag plays the video as expected. However, I can't get this to work on iPhones (Mobile Safari). The Get() method is never called even after pressing the play button....

ASp.Net Identity Role manager


asp.net,vb.net,webforms,sql-server-2012,asp.net-identity
I am using Visual Studio 2013. I have a ASP.net (vb) Webforms site with asp.net identity. I trying to create a page that manages User role and create roles. I cant find any help online for this when it comes to web forms. This code works for asp.net membership but...

Invalidate user credentials when password changes


asp.net,asp.net-mvc,security,asp.net-identity
I have an Asp.net MVC website. When the users change their password, do the logins from all of the browsers invalidate? I mean will the user require to login on all browsers with the new password? If not, is there a way to do this?

Store does not implement IUserLockoutStore


asp.net-mvc-5,asp.net-identity
I'm trying to implement own DAL for asp.net Identity 2.0 with functionality that I need. I don't need Account Lockout functionality. But When I try to call var result = await SignInManager.PasswordSignInAsync(model.Login, model.Password, model.RememberMe, shouldLockout: false); I get System.NotSupportedException:Store does not implement IUserLockoutStore<TUser>. So why should I need to implement...

Route parameter with slash “/” in URL


asp.net-web-api,routing,asp.net-web-api2,asp.net-web-api-routing,attributerouting
I know you can apply a wildcard in the route attribute to allow / such as date input for example: [Route("orders/{*orderdate}")] The problem with wildcard is only applicable to the last paramter in URI. How do I solve the issue if want to have the following URI: [Route("orders/{orderdate}/customers")] ? EDIT:...

What set's the User.Identity.Name and User.Identity.IsAuthenticated?


asp.net,asp.net-mvc,asp.net-identity,iprincipal,iidentity
I want to know what set's the user identity name and change isAuthenticatedto true. Why is User.Identity.Name an empty string and User.Identity.IsAuthenticated false after SignInManager.PasswordSignInAsync has returned Success. // POST: /Account/Login [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<ActionResult> Login(LoginViewModel model, string returnUrl) { if (!ModelState.IsValid) { return View(model); } var userIdentityNameTest...

web api FromUri and FromBody attributes misunderstanding


asp.net-web-api,web-api,asp.net-web-api2
I found this example in google: public string GetValue([FromUri]Book b, [FromUri]Author a) { return b.Name + " ("+a.AuthorName+")"; } public string PostValue([FromBody]Person p) { return p.FirstName; } I can't understand what is the point of [FromUri] attribute if HTTP GET method send data only as part of the URl respectively,...

ASP.NET MVC Blacklist for Roles/Users


c#,asp.net,asp.net-mvc,asp.net-identity,authorize-attribute
Question Summary: In ASP.NET MVC, is there a clean way to prevent a specific user or role from accessing an action? Obviously, the following would allow roles Admin and Editor to access the entire controller. [Authorize(Roles = "Admin, Editor")] public class HomeController : Controller { public ActionResult Index() { return...

MVC Identity 2 - Logout on browser or tab close


asp.net-mvc,asp.net-identity,asp.net-identity-2
I need to log out a user if he closes the browser/tab running my website. I have set the isPersistant bool to false, yet it does not log the user out. I want force the user to log in again if the tab is closed, I don't want to use...

Autofac - DelegatingHandler (HttpMessageHandler) Registration


c#,web-api,asp.net-web-api2,autofac,ioc-container
I have a custom DelegatingHandler in a class library that I need to register with Autofac. The webapi host resolves it's dependencies on runtime, so the host has no references to this library. public class LocalizationHandler : DelegatingHandler { protected override async Task<HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken cancellationToken ) {}...

Changing password asp.net identity


asp.net-mvc,asp.net-identity
Is there a quick way to verify is user exists and based on existence of user name get user id? (i.e. the user only has the user name and the adds it to change their password)? I would think something like this... String userId = User.Identity.GetUserId(userName); I am looking for...

Adding User Authentication to MVC


asp.net,asp.net-mvc,entity-framework,asp.net-identity
I was assigned my first ever MVC 5 projet, it is a simple Lending System with lots of CRUD operations which is almost done except that I have not implemented user authentication to the app yet. My project has 4 layers: 1. App.Web - mvc web app 2. App.DataAccess -...

PostAsync to /Token returns Internal server error


c#,asp.net,asp.net-web-api2
I have a web Api with a route to the Login Token setup in the Startup.Auth like so: PublicClientId = "self"; OAuthOptions = new OAuthAuthorizationServerOptions { TokenEndpointPath = new PathString("/Token"), Provider = new ApplicationOAuthProvider(PublicClientId), AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"), AccessTokenExpireTimeSpan = TimeSpan.FromDays(1), AllowInsecureHttp = false }; That should route my api...

How to get the current logged in user Id ASP.NET MVC6


asp.net,asp.net-identity,asp.net-mvc-6
I've done this before with MVC5 using User.Identity.GetUserId() but that doesn't seem to work here. The User.Identity doesnt have the GetUserId() method I am using Microsoft.AspNet.Identity...

Validation of asp.net identity password


c#,asp.net,.net,asp.net-mvc,asp.net-identity
I have an asp.net mvc application, in which I used the Asp.net identity. I implemented this method to validate a collaborator ( customisation of user) fields : [HttpPost] public bool ValidateCollaborateur(CollaborateurModel item) { if (item.Username == null || item.Email == null) return false; if (UserManager.FindByEmail(item.Email) != null) return false; return...

How to define multiple partial Owin Startup classes and have them all run their code


asp.net,asp.net-mvc,asp.net-mvc-5,asp.net-identity,owin
I'm working on an MVC application that will feature a "plugin" architecture. Basically there will be a main "host" project that will dynamically load other projects at runtime. We want to move all ASP.NET Identity related stuff into its own separate plugin project. The main host project already contains an...

Can I receive a JavaScript Object on an API WITHOUT a Corresponding C# Object?


javascript,c#,asp.net-web-api2
I have a Web API 2 controller. I am sending a JavaScript Object from the client in a call: myObject = {propertyOne: 'Hi', propertyTwo: 'Bye'} Do I HAVE to make a class with those properties in C# to receive the object as an argument to the Web API controller? public...

how to update multiple data in entityframework through async web api


entity-framework,asp.net-web-api,async-await,web-api,asp.net-web-api2
I am using web api 2, and entity framework 6. I have created an async web api, which updates all the records at once. I am also using Autofac for dependency injection. My service interface is as follows : Task<Approval> TakeAction(int id, bool isApprove) void TakeAction(bool isApprove) These are my...

How can I cast/convert an anonymous type from HttpResponseMessage for unit testing?


unit-testing,c#-4.0,asp.net-web-api2,mstest,anonymous-types
I have been tasked with writing a unit test for the following Web API 2 action: public HttpResponseMessage Get() { IEnumerable<KeyValuePair<long, string>> things = _service.GetSomething(); return ActionContext.Request.CreateResponse(things.Select(x => new { Thing1 = x.Prop1.ToString(), Thing2 = x.Prop2 }).ToArray()); } I am testing the status code and that works fine, but I...

Is it considered bad practice to reference the Microsoft.AspNet.Identity in the service layer of a multi layered web application?


c#,asp.net,asp.net-mvc,security,asp.net-identity
In my MVC application I am currently setting the Thread.CurrentPrincipal = HttpContext.Current.User in the Application_PostAuthenticateRequest() method e.g. protected void Application_PostAuthenticateRequest() { Thread.CurrentPrincipal = HttpContext.Current.User; } This allows me to use the Thread.CurrentPrincipal in other assemblies i.e. the service layer. For example: using System.Security; using System.Security.Permissions; using System.Threading; using Microsoft.AspNet.Identity; namespace...

How to change PasswordValidator in MVC6


asp.net-mvc,asp.net-identity,asp.net-5,asp.net-mvc-6
In the Asp.Net MVC 5 using Identity, was possible to do the following: manager.PasswordValidator = new PasswordValidator { RequiredLength = 6, RequireLowercase = true, RequireDigit = false, RequireUppercase = false }; How to change the same configuration in MVC 6? I see that can be in ConfigurationServices method in the...

Web API Returning a 405. Shouldn't it be a 404?


rest,asp.net-web-api,asp.net-web-api2,asp.net-web-api-routing
I've got a VendorsController that supports GET (by id) and POST (with a model). They are working as expected when called through the intended routes. However, I noticed that if I add an id to the POST route (ie add "/5" to "api/vendors"), I get a 405, with Response Body...

Unit testing ASP.NET Web API 2 Controller which returns custom result


c#,.net,unit-testing,asp.net-web-api,asp.net-web-api2
I have a Web API 2 controller which has an action method like this: public async Task<IHttpActionResult> Foo(int id) { var foo = await _repository.GetFooAsync(id); return foo == null ? (IHttpActionResult)NotFound() : new CssResult(foo.Css); } Where CssResult is defined as: public class CssResult : IHttpActionResult { private readonly string _content;...