Click here to Skip to main content
15,921,793 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am new to MVC5. Please help.

Following is the Controller class decorated with <authorize> Attribute.
The Authorize Attribute is at Class level and at Action level too.
I want to access Users and Roles in the Controller and Action, it belongs to.
How to write the [Magic Code] for this?
I am trying to have Authorization and Authentication with built-in MVC Authorize.
I want to use Database for Authentication.
My plan is to write my own code in Action Method for Authorization and Authentication or give a call to generic function.


<Authorize(Users:="User1,User3", Roles:="Role1"Role2")>
Public Class AbcController : Inherits Controller
.
.
.
<Authorize(Users:="User2,User4"), Roles:="Role3,Role4">
Public Function XyzAction() As ActionResult
.
.
.
dim s1, s2, s3, s4 as String
' The Magic Code here...
' THEN, values of S1 to s4 are expected as:
s1 => "User2,User4"
s2 => "Role1,Role2"
s3 => "User2,User4" and
s4 => "Role3,Role4"
.
.
.
End Function
.
.
.
End Class

What I have tried:

I tried too many things including:
Overriding method OnAuthorization
Using Roles.GetRolesForUser(User.Identity.Name)
Read many articales but not found any of use.
Many times thought, Is it possible?
Posted
Updated 24-Sep-18 4:50am

1 solution

I've written a series of articles about ASP.NET MVC 5 that includes Authorization and Authentication a while back. Here's the direct link: ASP.NET MVC 5: Building Your First Web Application - Part 2[^]

If you are new to ASP.NET MVC then I would recommend you to start at Part 1 so you can have a better understanding how stuff works in MVC: ASP.NET MVC 5: Building Your First Web Application - Part 1[^]

PS: The code used in the article is in C# but it should be pretty self-explanatory. Just use an online converter tool to convert C# to VB.NET: Code Converter C# to VB and VB to C# – Telerik[^]
 
Share this answer
 
v2
Comments
satbhai 26-Sep-18 4:34am    
Thanks a lot Sir.

Now there are two Data Annotations to my Action Method as follows:

' GET: Home/AboutUs
' Here, Users are "User01 and "User03" and Roles are "manager and SystemUser"
<Authenticate("Manager", "SystemUser")>
<authorize(users:="user01,user03")>
Function AboutUs() As ActionResult
Return View()
End Function

Now Authenticate works perfect. User exists but Role Not.
I am also able to show message, "You are not authenticated for this Page"

Such Message I want to give when User absent irrespective of Role existance.
like: You are not Authorized for this Page.
How should I achieve this?

Tried, but not got yet...

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900