Ejemplo n.º 1
0
        public static void ConfigureOAuthTokenGeneration(IAppBuilder app)
        {
            // configure database context and user manager to use a single instance per request
            app.CreatePerOwinContext(ngk.DataLayer.EFDbContext.AuthorizationContext.Create);
            app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);

            app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);

            var token = new CustomJwtFormat("ngKBaseAngular");

            OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
            {
                // production should not allow insecure http
                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString("/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(20),
                Provider = new Providers.CustomOAuthProvider(),
                RefreshTokenProvider = new Providers.RefreshTokenProvider(),
                AccessTokenFormat = token
            };

            // OAuth 2.0 Bearer Access Token Generation
            app.UseOAuthAuthorizationServer(OAuthServerOptions);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
        }
Ejemplo n.º 2
0
 private async Task<string> GenerateUserToken(ApplicationUser validatedUser)
 {
     CustomJwtFormat jwt = new CustomJwtFormat("http://jv.com");
     var identity = await validatedUser.GenerateUserIdentityAsync(AppUserManager, "password");
     Microsoft.Owin.Security.AuthenticationProperties properties = new Microsoft.Owin.Security.AuthenticationProperties();
     properties.IssuedUtc = DateTime.Now.ToUniversalTime();
     properties.ExpiresUtc = DateTime.Now.AddMinutes(5).ToUniversalTime();
     return jwt.Protect(new Microsoft.Owin.Security.AuthenticationTicket(identity, properties));
 }
Ejemplo n.º 3
0
 protected void Application_Start()
 {
     AreaRegistration.RegisterAllAreas();
     System.Web.Http.GlobalConfiguration.Configure(WebApiConfig.Register);
     FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
     RouteConfig.RegisterRoutes(RouteTable.Routes);
     BundleConfig.RegisterBundles(BundleTable.Bundles);
     CustomJwtFormat.GenerateClientCredentials("Privacy Passport V1");
 }
Ejemplo n.º 4
0
        private async Task <string> GenerateUserToken(ApplicationUser validatedUser)
        {
            CustomJwtFormat jwt      = new CustomJwtFormat("http://jv.com");
            var             identity = await validatedUser.GenerateUserIdentityAsync(AppUserManager, "password");

            Microsoft.Owin.Security.AuthenticationProperties properties = new Microsoft.Owin.Security.AuthenticationProperties();
            properties.IssuedUtc  = DateTime.Now.ToUniversalTime();
            properties.ExpiresUtc = DateTime.Now.AddMinutes(5).ToUniversalTime();
            return(jwt.Protect(new Microsoft.Owin.Security.AuthenticationTicket(identity, properties)));
        }
        public JwtOAuthOptions()
        {
            TokenEndpointPath         = new PathString("/api/Token");
            AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(60);
            AccessTokenFormat         = new CustomJwtFormat(this);
            Provider = new JwtOAuthProvider();
#if DEBUG
            AllowInsecureHttp = true;
#endif
        }
Ejemplo n.º 6
0
        private static void ConfigureJwtConsumer(IAppBuilder app)
        {
            var accessTokenFormat = new CustomJwtFormat(
                Registry.OAuthAllowedAudience,
                Registry.OAuthIssuer,
                Registry.OAuthBase64Secret,
                Registry.OAuthAccessTokenExpireSeconds);

            var options = new OAuthBearerAuthenticationOptions
            {
                AuthenticationType = "Bearer",
                AuthenticationMode = AuthenticationMode.Active,
                AccessTokenFormat  = accessTokenFormat
            };

            app.UseOAuthBearerAuthentication(options);
        }
Ejemplo n.º 7
0
        public void ConfigureOAuth(IAppBuilder app)
        {
            var issuer = ConfigurationManager.AppSettings["issuer"];

            app.CreatePerOwinContext(() => new CustomUserManager(new CustomUserStore(new UsersAuthorizationStore())));

            app.UseCookieAuthentication(new CookieAuthenticationOptions());
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions
            {
                TokenEndpointPath         = new PathString("/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30),
                Provider          = new CustomOAuthProvider(),
                AccessTokenFormat = new CustomJwtFormat(issuer),
#if DEBUG
                AllowInsecureHttp = true
#else
                AllowInsecureHttp = false
#endif
            });
Ejemplo n.º 8
0
        private JObject GenerateLocalAccessTokenResponse(string userName, List <string> roleList, string clientId)
        {
            var tokenExpirationMinutes = Helper.GetTokenExpirationMinutes();
            var tokenExpiration        = TimeSpan.FromMinutes(tokenExpirationMinutes);

            var ticket = Helper.GetJwtAuthenticationTicket(userName, roleList, clientId);

            var customJwtFormat = new CustomJwtFormat(_tokenIssuer);

            var accessToken = customJwtFormat.Protect(ticket);

            JObject tokenResponse = new JObject(
                new JProperty("userName", userName),
                new JProperty("access_token", accessToken),
                new JProperty("token_type", "bearer"),
                new JProperty("expires_in", tokenExpiration.TotalSeconds.ToString()),
                new JProperty(".issued", ticket.Properties.IssuedUtc.ToString()),
                new JProperty(".expires", ticket.Properties.ExpiresUtc.ToString())
                );

            return(tokenResponse);
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Generate a valid token for a user from controller
        /// </summary>
        /// <param name="user">The logged in user</param>
        /// <returns></returns>
        protected async Task <JObject> GenerateLocalAccessToken(PhongTroUser user)
        {
            var userManager = HttpContext.Current.GetOwinContext().GetUserManager <PhongTroUserManager>();

            var validTime = TimeSpan.FromDays(1);
            var identity  = await userManager.CreateIdentityAsync(user, JWTAuthenticationType);

            var jwtFormat = new CustomJwtFormat(ConfigurationManager.AppSettings[KeyTokenIssuer]);
            var authenticationProperties = new AuthenticationProperties()
            {
                IssuedUtc  = DateTimeOffset.UtcNow,
                ExpiresUtc = DateTimeOffset.UtcNow.Add(validTime)
            };
            var authenticationTicket = new AuthenticationTicket(identity, authenticationProperties);
            var token = jwtFormat.Protect(authenticationTicket);

            JObject response = new JObject(
                new JProperty(KeyResponseToken, token),
                new JProperty(KeyResponseType, TokenType),
                new JProperty(KeyResponseExpire, validTime.TotalSeconds.ToString()));

            return(response);
        }
Ejemplo n.º 10
0
        // GET: Lti
        public async Task <ActionResult> LtiEntry()
        {
            var isLti = Request.IsAuthenticatedWithLti();

            if (!isLti)
            {
                return(null);
            }

            var ltiRequest = new LtiRequest();

            ltiRequest.ParseRequest(Request);

            var person = new Person();

            try
            {
                person = await _userRepo.ProcessLtiUser(ltiRequest);
            }
            catch (InvalidEmailException ex)
            {
                ViewBag.Error = ex.Message + "\n\n Please update your email address in both the LMS and AU Portal to use ECAT.";
                return(View());
            }
            catch (UserUpdateException) {
                ViewBag.Error = "There was an error updating your account with the information from the LMS. Please try again.";
                return(View());
            }

            var token = new IdToken
            {
                TokenExpire        = DateTime.Now.Add(TimeSpan.FromHours(24)),
                TokenExpireWarning = DateTime.Now.Add(TimeSpan.FromHours(23)),
                LastName           = person.LastName,
                FirstName          = person.FirstName,
                Email                = person.Email,
                MpAffiliation        = person.MpAffiliation,
                MpComponent          = person.MpComponent,
                MpPaygrade           = person.MpPaygrade,
                MpGender             = person.MpGender,
                MpInstituteRole      = person.MpInstituteRole,
                RegistrationComplete = person.RegistrationComplete,
                PersonId             = person.PersonId
            };

            var identity = UserAuthToken.GetClaimId;

            identity.AddClaim(new Claim(ClaimTypes.PrimarySid, token.PersonId.ToString()));

            switch (person.MpInstituteRole)
            {
            case MpInstituteRoleId.Faculty:
                //person.Faculty = null;
                identity.AddClaim(new Claim(ClaimTypes.Role, RoleMap.Faculty.ToString()));
                if (person.Faculty.IsCourseAdmin)
                {
                    identity.AddClaim(new Claim(ClaimTypes.Role, MpInstituteRole.ISA));
                }
                else
                {
                    identity.AddClaim(new Claim(ClaimTypes.Role, MpInstituteRole.notISA));
                }
                break;

            case MpInstituteRoleId.Student:
                identity.AddClaim(new Claim(ClaimTypes.Role, RoleMap.Student.ToString()));
                break;

            default:
                identity.AddClaim(new Claim(ClaimTypes.Role, RoleMap.External.ToString()));
                break;
            }

            var ticket = new AuthenticationTicket(identity, new AuthenticationProperties());

            ticket.Properties.IssuedUtc  = DateTime.Now;
            ticket.Properties.ExpiresUtc = DateTime.Now.AddHours(24);

            //token.AuthToken = AuthServerOptions.OabOpts.AccessTokenFormat.Protect(ticket);
            var format = new CustomJwtFormat(ConfigurationManager.AppSettings["issuer"]);

            token.AuthToken = format.Protect(ticket);

            ViewBag.User = JsonConvert.SerializeObject(token, Formatting.None,
                                                       new JsonSerializerSettings
            {
                ContractResolver      = new CamelCasePropertyNamesContractResolver(),
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
            });

            return(View());
        }