Authentication using OAuth in MVC

 

Scenario:

User Authentication using OAuth for MVC

Solution:

         MVC Auth Filter
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    public class AuthFilter : ActionFilterAttribute
        {
            public override void OnActionExecuting(ActionExecutingContext filterContext)
            {
                //Check if Access Token is present in request
                if (_authServ.TryParseAccessToken(filterContext.HttpContext))
                {
                    //Validate the Access Token
                    var result = _authServ.ValidateAccessToken(filterContext.HttpContext);
                }
                else if (tokenexired)
                {
                    //refresh the token
                    RefreshAccessToken();
                }
                else
                {
                    //else authenticate
                    Authenticate(filterContext.HttpContext);
                }
            }
        }
          Auth Service, internally calling OAuth service
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    public class AuthServ
        {
            public bool ParseToken(HttpContextBase context)
            {
                return !string.IsNullOrEmpty(context.Request.QueryString["token"]);
            }
            public bool ValidateToken(HttpContextBase context)
            {
                var webClient = new WebClient();
    
                webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
    
                var data = webClient.UploadString("/TokenProvider/Validate?grant_type=code&client_id=&client_secret=&accessToken=",
                    authUrl,
                    HttpUtility.UrlEncode(clientId),
                    HttpUtility.UrlEncode(clientSecret),
                    accessToken, "POST", "");
            }
    
            public void RefreshToken()
            {
                context.Response.Redirect(string.Format("TokenProvider/Index?grant_type=refresh_token&client_id=&client_secret=&refreshToken=&accessToken=&return_url=&callback_url=");
            }
    
            public string Authenticate(HttpContextBase context)
            {
                context.Response.Redirect("/TokenProvider/Index?grant_type=code&client_id=&client_secret=&return_url=&callback_url=&userId=");
            }
        }

No comments:

Post a Comment

Move Github Sub Repository back to main repo

 -- delete .gitmodules git rm --cached MyProject/Core git commit -m 'Remove myproject_core submodule' rm -rf MyProject/Core git remo...