public static void AddOpenIdConnectIntercepts(this OpenIdConnectOptions opts) { opts.Events = new OpenIdConnectEvents { OnAuthorizationCodeReceived = async ctx => { var request = ctx.HttpContext.Request; var currentUri = UriHelper.BuildAbsolute(request.Scheme, request.Host, request.PathBase, request.Path); var credential = new ClientCredential(ctx.Options.ClientId, ctx.Options.ClientSecret); var distributedCache = ctx.HttpContext.RequestServices.GetRequiredService <IDistributedCache>(); string userId = ctx.Principal.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value; var cache = new AdalDistributedTokenCache(distributedCache, userId); var authContext = new AuthenticationContext(ctx.Options.Authority, cache); var result = await authContext.AcquireTokenByAuthorizationCodeAsync( ctx.ProtocolMessage.Code, new Uri(currentUri), credential, ctx.Options.Resource); ctx.HandleCodeRedemption(result.AccessToken, result.IdToken); } }; }
public void ConfigureServices(IServiceCollection services) { services.AddMvc(opts => { opts.Filters.Add(typeof(AdalTokenAcquisitionExceptionFilter)); }); services.AddAuthorization(o => { }); services.Configure <OpenIdConnectOptions>(Configuration.GetSection("OpenIDAuthentication")); services.AddAuthentication(auth => { auth.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme; auth.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme; auth.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme; }) .AddCookie() .AddOpenIdConnect(opts => { Configuration.GetSection("OpenIDAuthentication").Bind(opts); //opts.Scope.Add("email"); //opts.Scope.Add("profile"); opts.Events = new OpenIdConnectEvents { OnAuthorizationCodeReceived = async ctx => { HttpRequest request = ctx.HttpContext.Request; string currentUri = UriHelper.BuildAbsolute(request.Scheme, request.Host, request.PathBase, request.Path); var credential = new ClientCredential(ctx.Options.ClientId, ctx.Options.ClientSecret); IDistributedCache distributedCache = ctx.HttpContext.RequestServices.GetRequiredService <IDistributedCache>(); string userId = ctx.Principal.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value; var cache = new AdalDistributedTokenCache(distributedCache, userId); var authContext = new AuthenticationContext(ctx.Options.Authority, cache); AuthenticationResult result = await authContext.AcquireTokenByAuthorizationCodeAsync( ctx.ProtocolMessage.Code, new Uri(currentUri), credential, ctx.Options.Resource); ctx.HandleCodeRedemption(result.AccessToken, result.IdToken); }, OnRemoteFailure = context => { context.Response.Redirect("/"); context.HandleResponse(); return(System.Threading.Tasks.Task.FromResult(0)); } }; }); }
private async Task <string> GetAccessTokenAsync() { string authority = _config["Authentication:Authority"]; string userId = User.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value; var cache = new AdalDistributedTokenCache(_cache, userId); var authContext = new AuthenticationContext(authority, cache); string clientId = _config["Authentication:ClientId"]; string clientSecret = _config["Authentication:ClientSecret"]; var credential = new ClientCredential(clientId, clientSecret); var result = await authContext.AcquireTokenSilentAsync("https://graph.microsoft.com", credential, new UserIdentifier(userId, UserIdentifierType.UniqueId)); return(result.AccessToken); }
/// <summary> /// Configures the services. /// </summary> /// <param name="services">The services.</param> /// <remarks> /// This method gets called by the runtime. Use this method to add services to the container. /// </remarks> public void ConfigureServices(IServiceCollection services) { services.AddDbContext <Briteplan>(options => options.UseSqlServer(Configuration["Data:ConnectionStrings:BloggingDatabase"])); services.AddAuthorization(ConfigureAuthPolicies()); services.AddSingleton <IAuthorizationHandler, CheckUserRoleHandler>(); services.AddAuthentication(auth => { auth.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; auth.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme; auth.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme; auth.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme; }).AddBpJwtBearer(options => Configuration.Bind("TokenOptions", options)) .AddCookie().AddOpenIdConnect(opts => { Configuration.GetSection("Authentication").Bind(opts); opts.Events = new OpenIdConnectEvents { OnAuthorizationCodeReceived = async ctx => { var request = ctx.HttpContext.Request; var currentUri = UriHelper.BuildAbsolute(request.Scheme, request.Host, request.PathBase, request.Path); var credential = new ClientCredential(ctx.Options.ClientId, ctx.Options.ClientSecret); var distributedCache = ctx.HttpContext.RequestServices.GetRequiredService <IDistributedCache>(); var userId = ctx.Principal.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value; var cache = new AdalDistributedTokenCache(distributedCache, userId); var authContext = new AuthenticationContext(ctx.Options.Authority, cache); var result = await authContext.AcquireTokenByAuthorizationCodeAsync(ctx.ProtocolMessage.Code, new Uri(currentUri), credential, ctx.Options.Resource); var requiredService = ctx.HttpContext.RequestServices.GetRequiredService <IResourceManager>(); var resource = await requiredService.GetByUsername(result.UserInfo.DisplayableId); if (resource != null) { var claims = new List <Claim> { new Claim(YstervarkClaimNames.ResourceName, resource.ResourceName), new Claim(YstervarkClaimNames.ResourceId, resource.ResourceId.ToString()), new Claim(YstervarkClaimNames.TenantId, resource.TenantId.ToString()), new Claim(JwtRegisteredClaimNames.Email, resource.Emailaddress), }; claims.AddRange(resource.ResourceRole.Select(roleModel => new Claim(ClaimsIdentity.DefaultRoleClaimType, roleModel.Role.RoleName))); ctx.Principal.AddIdentity(new ClaimsIdentity(claims)); } else { ctx.Fail(new UnauthorizedAccessException()); return; } ctx.HandleCodeRedemption(result.AccessToken, result.IdToken); } }; }); services.AddMvc().AddJsonOptions(j => { j.SerializerSettings.ContractResolver = new DefaultContractResolver(); j.SerializerSettings.NullValueHandling = NullValueHandling.Ignore; }); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Title = "Ystervark", Version = "v1", Contact = new Contact { Email = "*****@*****.**", Name = "Richard Bailey", Url = "https://github.com/Programm3r" } }); }); services.AddSignalR(); }