Ejemplo n.º 1
0
        public static Line GetUserInfoLine(string token, string token_id)
        {
            try
            {
                WebClient wc = new WebClient();
                wc.Encoding = System.Text.Encoding.UTF8;
                wc.Headers.Clear();
                wc.Headers.Add("Authorization", "Bearer " + token);

                //get
                string JSON             = wc.DownloadString("https://api.line.me/v2/profile");
                var    JwtSecurityToken = new System.IdentityModel.Tokens.JwtSecurityToken(token_id);
                var    email            = "";
                //如果有email
                if (JwtSecurityToken.Claims.ToList().Find(c => c.Type == "email") != null)
                {
                    email = JwtSecurityToken.Claims.First(c => c.Type == "email").Value;
                }

                //parsing JSON
                var Result = Newtonsoft.Json.JsonConvert.DeserializeObject <Line>(JSON);
                Result.email = email;
                return(Result);
            }
            catch (WebException ex)
            {
                using (var reader = new System.IO.StreamReader(ex.Response.GetResponseStream()))
                {
                    var responseText = reader.ReadToEnd();
                    throw new Exception("GetUserInfo: " + responseText, ex);
                }
            }
        }
Ejemplo n.º 2
0
        public string Protect(AuthenticationTicket data)
        {
            if (data == null)
            {
                throw new ArgumentNullException("data");
            }

            string audienceId = ConfigurationManager.AppSettings["audienceId"];

            string symmetricKeyAsBase64 = ConfigurationManager.AppSettings["audienceSecret"];

            var keyByteArray = TextEncodings.Base64Url.Decode(symmetricKeyAsBase64);

            var signingKey = new HmacSigningCredentials(keyByteArray);

            var issued = data.Properties.IssuedUtc;

            var expires = data.Properties.ExpiresUtc;

            var token = new System.IdentityModel.Tokens.JwtSecurityToken(_issuer, audienceId, data.Identity.Claims, issued.Value.UtcDateTime, expires.Value.UtcDateTime, signingKey);

            var handler = new System.IdentityModel.Tokens.JwtSecurityTokenHandler();

            var jwt = handler.WriteToken(token);

            return(jwt);
        }
Ejemplo n.º 3
0
        public virtual ActionResult OAuth2callback(string state, string code)
        {
            if (state != "foobar")
            {
                return(RedirectToAction(Actions.LogOn()));
            }
            string responseContent = "";

            try
            {
                var post = string.Format("code={0}&client_id={1}&client_secret={2}&redirect_uri={3}&grant_type={4}"
                                         , HttpUtility.UrlEncode(code)
                                         , HttpUtility.UrlEncode(google_clientid)
                                         , HttpUtility.UrlEncode(google_clientsecret)
                                         , HttpUtility.UrlEncode(Google_RedirectUri)
                                         , HttpUtility.UrlEncode("authorization_code"));

                var request = (HttpWebRequest)HttpWebRequest.Create("https://accounts.google.com/o/oauth2/token");
                request.Method            = "POST";
                request.AllowAutoRedirect = false;
                request.ContentType       = "application/x-www-form-urlencoded";
                using (var stOut = new StreamWriter(request.GetRequestStream(), System.Text.Encoding.ASCII))
                {
                    stOut.Write(post);
                    stOut.Close();
                }

                var httpResponse = (HttpWebResponse)request.GetResponse();
                using (var resStream = new StreamReader(httpResponse.GetResponseStream(), Encoding.ASCII))
                {
                    responseContent = resStream.ReadToEnd();
                }
            }
            catch (Exception e)
            {
                return(Content("There was a problem with your request (" + e.Message + "). Please go back and try again."));
            }

            var reply        = JsonConvert.DeserializeObject <dynamic>(responseContent);
            var id_token     = reply["id_token"];
            var token        = new System.IdentityModel.Tokens.JwtSecurityToken(id_token.Value);
            var emailAddress = token.Claims.FirstOrDefault(x => x.Type == "email").Value;

            var username = CleanUpUsername(emailAddress);

            var user = this.Repository.GetUserByUsername(username);

            if (user == null || user.Disabled)
            {
                ViewBag.EmailAddress = emailAddress;
                return(View("NotAUser"));
            }

            FormsAuthentication.SetAuthCookie(user.Username, false);

            return(Redirect("~"));
        }
        internal static SPOnlineConnection InstantiateGraphAccessTokenConnection(string accessToken)
        {
#if NETSTANDARD2_0
            var jwtToken = new System.IdentityModel.Tokens.Jwt.JwtSecurityToken(accessToken);
#else
            var jwtToken = new System.IdentityModel.Tokens.JwtSecurityToken(accessToken);
#endif
            var tokenResult = new TokenResult();
            tokenResult.AccessToken = accessToken;
            tokenResult.ExpiresOn   = jwtToken.ValidTo;
            var spoConnection = new SPOnlineConnection(tokenResult, ConnectionMethod.AccessToken, ConnectionType.O365, 0, 0, 0, PnPPSVersionTag);
            spoConnection.ConnectionMethod = ConnectionMethod.GraphDeviceLogin;
            return(spoConnection);
        }
        //
        // The Client ID is used by the application to uniquely identify itself to Azure AD.
        // The App Key is a credential used to authenticate the application to Azure AD.  Azure AD supports password and certificate credentials.
        // The Metadata Address is used by the application to retrieve the signing keys used by Azure AD.
        // The AAD Instance is the instance of Azure, for example public Azure or Azure China.
        // The Authority is the sign-in URL of the tenant.
        // The Post Logout Redirect Uri is the URL where the user will be redirected after they sign out.
        //


        // This is the resource ID of the AAD Graph API.  We'll need this to request a token to call the Graph API.

        public void ConfigureAuth(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions());
            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
            {
                ClientId              = MediaLibraryWebApp.Configuration.ClientId,
                Authority             = MediaLibraryWebApp.Configuration.Authority,
                PostLogoutRedirectUri = MediaLibraryWebApp.Configuration.PostLogoutRedirectUri,
                Notifications         = new OpenIdConnectAuthenticationNotifications()
                {
                    //
                    // If there is a code in the OpenID Connect response, redeem it for an access token and refresh token, and store those away.
                    //
                    AuthorizationCodeReceived = (context) =>
                    {
                        var code = context.Code;
                        System.IdentityModel.Tokens.JwtSecurityToken jwtToken = context.JwtSecurityToken;
                        string userObjectID = context.AuthenticationTicket.Identity.FindFirst(MediaLibraryWebApp.Configuration.ClaimsObjectidentifier).Value;

                        Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential credential = new Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential(MediaLibraryWebApp.Configuration.ClientId, MediaLibraryWebApp.Configuration.AppKey);
                        NaiveSessionCache cache           = new NaiveSessionCache(userObjectID);
                        AuthenticationContext authContext = new AuthenticationContext(MediaLibraryWebApp.Configuration.Authority, cache);
                        //Getting a token to connect with GraphApi later on userProfile page
                        AuthenticationResult graphAPiresult = authContext.AcquireTokenByAuthorizationCode(code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, MediaLibraryWebApp.Configuration.GraphResourceId);

                        //Getting a access token which can be used to configure auth restrictions for multiple tentants since audience will be same for each web app requesting this token
                        AuthenticationResult kdAPiresult = authContext.AcquireTokenByAuthorizationCode(code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, MediaLibraryWebApp.Configuration.KdResourceId);
                        string kdAccessToken             = kdAPiresult.AccessToken;

                        //Initializing  MediaServicesCredentials in order to obtain access token to be used to connect
                        var amsCredentials = new MediaServicesCredentials(MediaLibraryWebApp.Configuration.MediaAccount, MediaLibraryWebApp.Configuration.MediaKey);
                        //Forces to get access token
                        amsCredentials.RefreshToken();

                        //Adding token to a claim so it can be accessible within controller
                        context.AuthenticationTicket.Identity.AddClaim(new Claim(MediaLibraryWebApp.Configuration.ClaimsSignInJwtToken, jwtToken.RawData));

                        //Adding media services access token as claim so it can be accessible within controller
                        context.AuthenticationTicket.Identity.AddClaim(new Claim(MediaLibraryWebApp.Configuration.ClaimsAmsAcessToken, amsCredentials.AccessToken));

                        return(Task.FromResult(0));
                    }
                }
            });
        }
Ejemplo n.º 6
0
        public static AuthResult FromADALAuthenticationResult(Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationResult authResult, Microsoft.IdentityModel.Clients.ActiveDirectory.TokenCache tokenCache)
        {
            var TokenClaim = new System.IdentityModel.Tokens.JwtSecurityToken(authResult.IdToken);
            var alias = TokenClaim.Claims.FirstOrDefault(m => m.Type == "upn").Value;
            var result = new AuthResult
            {
                AccessToken = authResult.AccessToken,
                IdToken = authResult.IdToken,
                UserName = $"{authResult.UserInfo.GivenName} {authResult.UserInfo.FamilyName}",
                UserUniqueId = authResult.UserInfo.UniqueId,
                ExpiresOnUtcTicks = authResult.ExpiresOn.UtcTicks,
                TokenCache = tokenCache.Serialize(),
                Alias = alias
            };

            return result;
        }
Ejemplo n.º 7
0
        public static AuthResult FromMSALAuthenticationResult(Microsoft.Identity.Client.AuthenticationResult authResult, Microsoft.Identity.Client.TokenCache tokenCache)
        {
            var TokenClaim = new System.IdentityModel.Tokens.JwtSecurityToken(authResult.IdToken);
            var alias = TokenClaim.Claims.FirstOrDefault(m => m.Type == "preferred_username").Value;

            var result = new AuthResult
            {
                AccessToken = authResult.Token,
                IdToken = authResult.IdToken,
                UserName = $"{authResult.User.Name}",
                UserUniqueId = authResult.User.UniqueId,
                ExpiresOnUtcTicks = authResult.ExpiresOn.UtcTicks,
                TokenCache = tokenCache.Serialize(),
                Alias = alias
            };

            return result;
        }
Ejemplo n.º 8
0
        private static void VerifyTokenContent(AuthenticationResultProxy result)
        {
            // Verify the token content confirms the user in AuthenticationResult.UserInfo
            var token = new System.IdentityModel.Tokens.JwtSecurityToken(result.AccessToken);

            foreach (var claim in token.Claims)
            {
                if (claim.Type == "oid")
                {
                    Verify.AreEqual(result.UserInfo.UniqueId, claim.Value);
                }

                if (claim.Type == "upn")
                {
                    Verify.AreEqual(result.UserInfo.DisplayableId, claim.Value);
                }
            }
        }
Ejemplo n.º 9
0
        public void ConfigureAuth(IAppBuilder app)
        {
            ApplicationDbContext db = new ApplicationDbContext();

            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
                {
                    ClientId = clientId,
                    Authority = Authority,
                    PostLogoutRedirectUri = postLogoutRedirectUri,

                    Notifications = new OpenIdConnectAuthenticationNotifications()
                    {
                        // If there is a code in the OpenID Connect response, redeem it for an access token and refresh token, and store those away.
                       AuthorizationCodeReceived = (context) =>
                       {
                           var code = context.Code;
                           ClientCredential credential = new ClientCredential(clientId, appKey);
                           string signedInUserID = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;
                           AuthenticationContext authContext = new AuthenticationContext(Authority, new ADALTokenCache(signedInUserID));
                           AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(
                               code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, graphResourceId);

                           // added by [email protected] to the original template
                           // Getting KeyDelivery Access Token
                           AuthenticationResult kdAPiresult = authContext.AcquireTokenByAuthorizationCode(
                               code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, kdResourceId);
                           string kdAccessToken = kdAPiresult.AccessToken;
                           System.IdentityModel.Tokens.JwtSecurityToken kdAccessJwtToken = new System.IdentityModel.Tokens.JwtSecurityToken(kdAccessToken);

                           //context.AuthenticationTicket.Identity.AddClaim(
                           //    new System.Security.Claims.Claim("KdAccessJwtSecurityTokenClaim", kdAccessJwtToken.RawData));
                           // added by [email protected] to the original template

                           return Task.FromResult(0);
                       }
                    }
                });
        }
        protected override void LoadUserAuthInfo(AuthUserSession userSession, IAuthTokens tokens, Dictionary <string, string> authInfo)
        {
            var idAuthTokens = tokens as IdentityServerAuthTokens;

            if (!string.IsNullOrWhiteSpace(idAuthTokens?.IdToken))
            {
#if NETSTANDARD1_6
                var jwtToken = new System.IdentityModel.Tokens.Jwt.JwtSecurityToken(idAuthTokens.IdToken);
#elif NET45
                var jwtToken = new System.IdentityModel.Tokens.JwtSecurityToken(idAuthTokens.IdToken);
#endif
                idAuthTokens.Issuer  = jwtToken.Issuer;
                idAuthTokens.Subject = jwtToken.Subject;

                foreach (var claim in jwtToken.Claims)
                {
                    switch (claim.Type)
                    {
                    case JwtClaimTypes.Expiration:
                        idAuthTokens.Expiration = claim.Value;
                        break;

                    case JwtClaimTypes.Audience:
                        idAuthTokens.Audience = claim.Value;
                        break;

                    case JwtClaimTypes.IssuedAt:
                        idAuthTokens.IssuedAt = claim.Value;
                        break;

                    case JwtClaimTypes.AuthenticationTime:
                        idAuthTokens.AuthenticationTime = claim.Value;
                        break;

                    case JwtClaimTypes.Nonce:
                        idAuthTokens.Nonce = claim.Value;
                        break;
                    }
                }
            }

            base.LoadUserAuthInfo(userSession, tokens, authInfo);
        }
Ejemplo n.º 11
0
        public static string MakeToken(string secret, string user)
        {
            var securityKey = new System.IdentityModel.Tokens.InMemorySymmetricSecurityKey(Encoding.Default.GetBytes(secret));

            System.IdentityModel.Tokens.SigningCredentials signingCredentials =
                new System.IdentityModel.Tokens.SigningCredentials(
                    securityKey,
                    "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256",
                    "http://www.w3.org/2001/04/xmlenc#sha256");

            byte[] randomNonce           = new Byte[32];
            RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();

            rng.GetBytes(randomNonce);

            List <Claim> claims = new List <Claim>()
            {
                new Claim("user", user),
                new Claim("nonce", Convert.ToBase64String(randomNonce)),
            };

            var jwtSecurityToken = new System.IdentityModel.Tokens.JwtSecurityToken(
                issuer,
                audience,
                claims,
                DateTime.Now,
                DateTime.Now.AddHours(1),
                signingCredentials
                );

            var handler = new System.IdentityModel.Tokens.JwtSecurityTokenHandler();

            string tokenString = handler.WriteToken(jwtSecurityToken);

            return(tokenString);
        }
Ejemplo n.º 12
0
        public static void ValidateToken(string tokenString, string secret)
        {
            var securityKey = new System.IdentityModel.Tokens.InMemorySymmetricSecurityKey(Encoding.Default.GetBytes(secret));

            var jwt = new System.IdentityModel.Tokens.JwtSecurityToken(tokenString);

            var tokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters()
            {
                ValidAudiences = new string[]
                {
                    audience
                },
                ValidIssuers = new string[]
                {
                    issuer
                },
                IssuerSigningKey = securityKey
            };

            System.IdentityModel.Tokens.SecurityToken validatedToken;
            var handler = new System.IdentityModel.Tokens.JwtSecurityTokenHandler();

            handler.ValidateToken(tokenString, tokenValidationParameters, out validatedToken);
        }
Ejemplo n.º 13
0
 public override void JwtLogin()
 {
     JwtToken = new System.IdentityModel.Tokens.JwtSecurityToken("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c");
 }
Ejemplo n.º 14
0
        public ActionResult Route()
        {
            string       userName       = Request["userName"];
            string       passWord       = Request["passWord"];
            string       authnlogin_but = Request["authnlogin_but"];
            string       oidclogin_but  = Request["oidclogin_but"];
            string       oidc_but       = Request["oidc_but"];
            string       location       = Request["location"];
            string       myStatus       = null;
            string       myStateToken;
            string       mySessionToken;
            string       myRelayState = null;
            string       myOktaId     = null;
            AuthResponse userAuthClientRsp;

            // set relayState
            //string relayState = Request["relayState"];
            //if (string.IsNullOrEmpty(relayState) && Request.QueryString["RelayState"] != null)
            //{
            //    relayState = Request.QueryString["RelayState"];
            //}
            //else if (string.IsNullOrEmpty(relayState) && TempData["relayState"] != null)
            //{
            //    relayState = (string)TempData["relayState"];
            //}
            //TempData["relayState"] = relayState;

            if (authnlogin_but == "Authn Sign In")
            {
                OktaClient oktaClient = new OktaClient(MvcApplication.apiToken, MvcApplication.apiUrl);
                try
                {
                    var usersClient = oktaClient.GetUsersClient();
                    var authClient  = oktaClient.GetAuthClient();
                    userAuthClientRsp = authClient.Authenticate(username: userName, password: passWord, relayState: myRelayState);
                    logger.Debug("thisAuth status " + userAuthClientRsp.Status);
                    myStatus       = userAuthClientRsp.Status;
                    myStateToken   = userAuthClientRsp.StateToken;
                    mySessionToken = userAuthClientRsp.SessionToken;
                    if (userAuthClientRsp.Embedded.User != null)
                    {
                        myOktaId = userAuthClientRsp.Embedded.User.Id;
                    }
                }
                catch (OktaException ex)
                {
                    if (ex.ErrorCode == "E0000004")
                    {
                        logger.Debug("Invalid Credentials for User: "******"errMessage"] = "Invalid Credentials for User: "******"E0000085")
                    {
                        logger.Debug("Access Denied by Polciy for User: "******"errMessage"] = "Access Denied by Polciy for User: "******"errMessage"] = appSettings["aicpa.DeniedNoteText"];
                    }
                    else
                    {
                        logger.Error(userName + " = " + ex.ErrorCode + ":" + ex.ErrorSummary);
                        // generic failure
                        TempData["errMessage"] = "Sign in process failed!";
                    }
                    TempData["userName"] = userName;
                    return(RedirectToAction("Login"));
                }

                switch (myStatus)
                {
                case "PASSWORD_WARN":      //password about to expire
                    logger.Debug("PASSWORD_WARN ");
                    //no action required
                    break;

                case "PASSWORD_EXPIRED":      //password has expired
                    logger.Debug("PASSWORD_EXPIRED ");
                    break;

                case "RECOVERY":      //user has requested a recovery token
                    logger.Debug("RECOVERY ");
                    //find which recovery mode sms, email is being used
                    //POST to next link
                    break;

                case "RECOVERY_CHALLENGE":      //user must verify factor specific recovery challenge
                    logger.Debug("RECOVERY_CHALLENGE ");
                    //verify the recovery factor
                    //POST to verify link
                    break;

                case "PASSWORD_RESET":         //user satified recovery and must now set password
                    logger.Debug("PASSWORD_RESET ");

                    //reset users password
                    //POST to next link
                    break;

                case "LOCKED_OUT":      //user account is locked, unlock required
                    logger.Debug("LOCKED_OUT ");
                    break;

                case "MFA_ENROLL":       //user must select and enroll an available factor
                    logger.Debug("MFA_ENROLL ");
                    break;

                case "MFA_ENROLL_ACTIVATE":       //user must activate the factor to complete enrollment
                    logger.Debug("MFA_ENROLL_ACTIVATE ");
                    //user must activate the factor
                    //POST to next link
                    break;

                case "MFA_REQUIRED":        //user must provide second factor with previously enrolled factor
                    logger.Debug("MFA_REQUIRED ");
                    break;

                case "MFA_CHALLENGE":          //use must verify factor specifc challenge
                    logger.Debug("MFA_CHALLENGE ");
                    break;

                case "SUCCESS":          //authentication is complete
                    logger.Debug("SUCCESS");
                    TempData["errMessage"] = "Authn Login Successful ";
                    TempData["oktaOrg"]    = MvcApplication.apiUrl;
                    //TempData["token"] = MvcApplication.apiToken;
                    string landingPage = null;
                    landingPage = location + "/AltLanding/UnprotectedLanding";
                    //if (string.IsNullOrEmpty(relayState))
                    //{
                    //    landingPage = location + "/AltLanding/UnprotectedLanding";
                    //}
                    //else
                    //{
                    //    landingPage = relayState;
                    //}


                    //option 1
                    //string redirectUrl = oktaSessionMgmt.SetSessionCookie(mySessionToken,landingPage);
                    //return Redirect(redirectUrl);

                    //option 2 - build redirectURL
                    //System.Text.StringBuilder redirectUrl = new System.Text.StringBuilder();
                    //string destLink = location + "/AltLanding/UnprotectedLanding";
                    //redirectUrl.Append(MvcApplication.apiUrl);
                    ////redirectUrl.Append("/login/sessionCookieRedirect?token=" + mySessionToken);
                    //redirectUrl.Append("/login/sessionCookieRedirect?checkAccountSetupComplete=true&token=" + mySessionToken);
                    //string encodedURL = HttpUtility.UrlEncode(destLink);
                    //redirectUrl.Append("&redirectUrl=" + encodedURL);
                    //return Redirect(redirectUrl.ToString());

                    //option 3 get session first, then set cookie
                    Session oktaSession = new Okta.Core.Models.Session();
                    oktaSession = oktaSessionMgmt.CreateSession(mySessionToken);
                    string cookieToken = oktaSession.CookieToken;
                    logger.Debug("session Id " + oktaSession.Id + " for User " + userName);
                    string redirectUrl = oktaSessionMgmt.SetSessionCookie(cookieToken, landingPage);
                    return(Redirect(redirectUrl));


                // break;
                default:
                    logger.Debug("Status: " + myStatus);
                    TempData["errMessage"] = "Status: " + myStatus;
                    break;
                }//end of switch
            }


            if (oidc_but == "Initiate Auth OIDC")
            {
                //version using Custom Authorization Server
                logger.Debug("Initiate OIDC Auth Code without Session");
                Random random    = new Random();
                string stateCode = random.Next(99999, 1000000).ToString();
                string oauthUrl  = appSettings["oidc.AuthServer"] + "/v1/authorize?response_type=code&response_mode=query&client_id=" + appSettings["oidc.spintweb.clientId"] + "&scope=" + appSettings["oidc.scopes"] + "&state=" + stateCode + "&nonce=CWBb0zHdZ92WqBLkyIuExu&redirect_uri=" + appSettings["oidc.spintweb.RedirectUri"];
                return(Redirect(oauthUrl));
            }

            if (oidc_but == "Initiate Implicit OIDC")
            {
                //version using Custom  Authorization Server
                logger.Debug("Initiate OIDC Implicit without Session");
                Random random    = new Random();
                string stateCode = random.Next(99999, 1000000).ToString();
                //string stateCode = "myStateInfo";
                string oauthUrl = appSettings["oidc.AuthServer"] + "/v1/authorize?response_type=id_token token&response_mode=form_post&client_id=" + appSettings["oidc.spintnative.clientId"] + "&scope=" + appSettings["oidc.scopes"] + "&state=" + stateCode + "&nonce=CWBb0zHdZ92WqBLkyIuExu&redirect_uri=" + appSettings["oidc.spintnative.RedirectUri"];
                //string oauthUrl = appSettings["oidc.AuthServer"] + "/v1/authorize?response_type=id_token token&response_mode=form_post&client_id=6788997876556&scope=" + appSettings["oidc.scopes"] + "&state=" + stateCode + "&nonce=CWBb0zHdZ92WqBLkyIuExu&redirect_uri=" + appSettings["oidc.spintnative.RedirectUri"];
                return(Redirect(oauthUrl));
            }



            if (oidc_but == "Initiate ResourceOwner OIDC")
            {
                string error                = null;
                string error_description    = null;
                string token_type           = null;
                string scope                = null;
                string id_token_status      = null;
                string idToken              = null;
                string access_token_status  = null;
                string accessToken          = null;
                string refresh_token_status = null;
                string refreshToken         = null;
                string jsonPayload          = null;


                IRestResponse <TokenRequestResponse> response = null;
                OidcIdTokenMin  oidcIdToken     = new OidcIdTokenMin();
                OidcAccessToken oidcAccessToken = new OidcAccessToken();
                string          basicAuth       = appSettings["oidc.spintnative.clientId"] + ":" + appSettings["oidc.spintnative.clientSecret"];

                var    bytesBasicAuth   = System.Text.Encoding.UTF8.GetBytes(basicAuth);
                string encodedBasicAuth = System.Convert.ToBase64String(bytesBasicAuth);

                try
                {
                    var client = new RestClient(appSettings["oidc.AuthServer"] + "/v1/token");
                    //var client = new RestClient(MvcApplication.apiUrl + "/oauth2/aus90h4gyj2Hc8QOy0h7/v1/token");
                    var request = new RestRequest(Method.POST);
                    request.AddHeader("Accept", "application/json");
                    request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
                    request.AddHeader("Authorization", " Basic " + encodedBasicAuth);
                    request.AddQueryParameter("grant_type", "password");
                    request.AddQueryParameter("username", userName);
                    request.AddQueryParameter("password", passWord);
                    request.AddQueryParameter("scope", appSettings["oidc.scopes"]);
                    request.AddQueryParameter("redirect_uri", appSettings["oidc.spintnative.RedirectUri"]);
                    response          = client.Execute <TokenRequestResponse>(request);
                    error             = response.Data.error;
                    error_description = response.Data.error_description;
                    token_type        = response.Data.token_type;
                    scope             = response.Data.scope;

                    if (response.Data.id_token != null)
                    {
                        idToken             = response.Data.id_token;
                        id_token_status     = "id_token present";
                        TempData["idToken"] = response.Data.id_token;
                        string clientId = appSettings["oidc.spintnative.clientId"];
                        string issuer   = appSettings["oidc.Issuer"];
                        string audience = appSettings["oidc.spintnative.clientId"];
                        jsonPayload = oktaOidcHelper.DecodeAndValidateIdToken(idToken, clientId, issuer, audience);
                        if (jsonPayload.Contains("Failure"))
                        {
                            TempData["errMessage"] = "Invalid ID Token!";
                        }
                        else
                        {
                            // TempData["errMessage"] = jsonPayload;
                            System.IdentityModel.Tokens.JwtSecurityToken tokenReceived = new System.IdentityModel.Tokens.JwtSecurityToken(idToken);
                            oidcIdToken = Newtonsoft.Json.JsonConvert.DeserializeObject <OidcIdTokenMin>(jsonPayload);
                        }
                    }
                    else
                    {
                        id_token_status = "id_token NOT present";
                    }

                    if (response.Data.access_token != null)
                    {
                        accessToken             = response.Data.access_token;
                        access_token_status     = "access_token present";
                        TempData["accessToken"] = response.Data.access_token;
                        System.IdentityModel.Tokens.JwtSecurityToken tokenReceived2 = new System.IdentityModel.Tokens.JwtSecurityToken(accessToken);
                    }
                    else
                    {
                        access_token_status = "access_token NOT present";
                    }

                    if (response.Data.refresh_token != null)
                    {
                        refreshToken         = response.Data.refresh_token;
                        refresh_token_status = "refresh_token present";
                    }
                    else
                    {
                        refresh_token_status = "refresh_token NOT present";
                    }
                }
                catch (Exception ex)
                {
                    logger.Error(ex.ToString());
                }
                if (accessToken != null || idToken != null)
                {
                    TempData["errMessage"] = "OIDC_Get Oauth Resource Owner SUCCESS token_type = " + token_type + " scope = " + scope + " : " + id_token_status + " : " + access_token_status + " oktaId = " + oidcIdToken.sub;
                    TempData["oktaOrg"]    = MvcApplication.apiUrl;
                    //TempData["token"] = MvcApplication.apiToken;

                    return(View("../AltLanding/ResOwnerLanding", oidcIdToken));
                }
                else
                {
                    TempData["errMessage"] = "OIDC_Get Oauth Resource Owner error " + error_description;
                    TempData["oktaOrg"]    = MvcApplication.apiUrl;
                    //TempData["token"] = MvcApplication.apiToken;
                    return(View("../AltLanding/UnprotectedLanding"));
                }
            }// end handle resource owner workflow



            if (oidc_but == "Client Credential Flow")
            {
                //this is available with Custom Authorization Server
                logger.Debug("Client Credential Flow");
                string error               = null;
                string error_description   = null;
                string token_type          = null;
                string scope               = null;
                string access_token_status = null;
                string accessToken         = null;
                string id_token_status     = null;
                string idToken             = null;
                System.IdentityModel.Tokens.JwtSecurityToken tokenReceived2 = null;
                System.IdentityModel.Tokens.JwtSecurityToken tokenReceived3 = null;
                string expires = null;
                IRestResponse <TokenRequestResponse> response = null;
                OidcIdToken     oidcIdToken     = new OidcIdToken();
                OidcAccessToken oidcAccessToken = new OidcAccessToken();
                string          basicAuth       = appSettings["oidc.clientcredservice.clientId"] + ":" + appSettings["oidc.clientcredservice.clientSecret"];

                var    bytesBasicAuth   = System.Text.Encoding.UTF8.GetBytes(basicAuth);
                string encodedBasicAuth = System.Convert.ToBase64String(bytesBasicAuth);


                var client  = new RestClient(appSettings["oidc.AuthServer"] + "/v1/token");
                var request = new RestRequest(Method.POST);
                // request.AddHeader("cache-control", "no-cache");
                request.AddHeader("Accept", "application/json");
                request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
                request.AddHeader("Authorization", " Basic " + encodedBasicAuth);
                request.AddQueryParameter("grant_type", "client_credentials");
                request.AddQueryParameter("scope", "clientCred_scope");
                response = client.Execute <TokenRequestResponse>(request);
                //error = response.Data.error;
                //error_description = response.Data.error_description;
                token_type = response.Data.token_type;
                scope      = response.Data.scope;
                expires    = response.Data.expires_in;

                if (response.Data.access_token != null)
                {
                    accessToken             = response.Data.access_token;
                    access_token_status     = "access_token present";
                    TempData["accessToken"] = response.Data.access_token;
                    tokenReceived2          = new System.IdentityModel.Tokens.JwtSecurityToken(accessToken);
                }
                else
                {
                    access_token_status = "access_token NOT present";
                }

                if (response.Data.id_token != null)
                {
                    idToken             = response.Data.id_token;
                    id_token_status     = "id_token present";
                    TempData["idToken"] = response.Data.id_token;
                    tokenReceived3      = new System.IdentityModel.Tokens.JwtSecurityToken(idToken);
                }
                else
                {
                    id_token_status = "id_token NOT present";
                }

                if (accessToken != null)
                {
                    TempData["errMessage"] = "Oauth Client Credentials SUCCESS token_type = " + token_type + " expires " + expires + " scope = " + scope + "  : " + access_token_status;
                    TempData["oktaOrg"]    = MvcApplication.apiUrl;
                    //TempData["token"] = MvcApplication.apiToken;
                    //GetInfoResponse getInfoResponse = new GetInfoResponse();
                    return(View("../AltLanding/ClientCredLanding"));
                }
                else
                {
                    TempData["errMessage"] = "Oauth Client Credentials Error token_type = " + token_type + " expires " + expires + " scope = " + scope + "  : " + access_token_status;
                    TempData["oktaOrg"]    = MvcApplication.apiUrl;
                    //TempData["token"] = MvcApplication.apiToken;
                    return(View("../AltLanding/UnprotectedLanding"));
                }
            }



            TempData["userName"] = userName;
            TempData["passWord"] = passWord;
            //return View("Login");
            return(RedirectToAction("UnprotectedLanding", "AltLanding"));
        }
        private static void VerifyTokenContent(AuthenticationResultProxy result)
        {

            // Verify the token content confirms the user in AuthenticationResult.UserInfo
            var token = new System.IdentityModel.Tokens.JwtSecurityToken(result.AccessToken);
            foreach (var claim in token.Claims)
            {
                if (claim.Type == "oid")
                {
                    Verify.AreEqual(result.UserInfo.UniqueId, claim.Value);
                }

                if (claim.Type == "upn")
                {
                    Verify.AreEqual(result.UserInfo.DisplayableId, claim.Value);
                }
            }
        }
Ejemplo n.º 16
0
        public virtual ActionResult OAuth2callback(string state, string code)
        {
            if (state != "foobar")
            {
                return RedirectToAction(Actions.LogOn());
            }
            string responseContent = "";
            try
            {
                var post = string.Format("code={0}&client_id={1}&client_secret={2}&redirect_uri={3}&grant_type={4}"
                    , HttpUtility.UrlEncode(code)
                    , HttpUtility.UrlEncode(google_clientid)
                    , HttpUtility.UrlEncode(google_clientsecret)
                    , HttpUtility.UrlEncode(Google_RedirectUri)
                    , HttpUtility.UrlEncode("authorization_code"));

                var request = (HttpWebRequest)HttpWebRequest.Create("https://accounts.google.com/o/oauth2/token");
                request.Method = "POST";
                request.AllowAutoRedirect = false;
                request.ContentType = "application/x-www-form-urlencoded";
                using (var stOut = new StreamWriter(request.GetRequestStream(), System.Text.Encoding.ASCII))
                {
                    stOut.Write(post);
                    stOut.Close();
                }

                var httpResponse = (HttpWebResponse)request.GetResponse();
                using (var resStream = new StreamReader(httpResponse.GetResponseStream(), Encoding.ASCII))
                {
                    responseContent = resStream.ReadToEnd();
                }
            }
            catch (Exception e)
            {
                return Content("There was a problem with your request (" + e.Message + "). Please go back and try again.");
            }

            var reply = JsonConvert.DeserializeObject<dynamic>(responseContent);
            var id_token = reply["id_token"];
            var token = new System.IdentityModel.Tokens.JwtSecurityToken(id_token.Value);
            var emailAddress =  token.Claims.FirstOrDefault(x => x.Type == "email").Value;

            var username = CleanUpUsername(emailAddress);

            var user = this.Repository.GetUserByUsername(username);
            if (user == null || user.Disabled)
            {
                ViewBag.EmailAddress = emailAddress;
                return View("NotAUser");
            }

            FormsAuthentication.SetAuthCookie(user.Username, false);

            return Redirect("~");
        }