Google calendar Add Event In ASP .net : Auth fail - asp.net-mvc

In my asp.net core app I'm going to add new event to google calendar. But it showing error in google. I have enabled calendar api and insert ClientId and ClientSecret. But it showing error.
This is my code below.
and
public void CreateEvent(string email, string text)
{
UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
new ClientSecrets
{
ClientId = "461480317556-xxxxxxxxxxg.apps.googleusercontent.com",
ClientSecret = "RljgIL79D2YFkmVaWQypCjIa",
},
new[] { CalendarService.Scope.Calendar },"user",CancellationToken.None).Result;
// Create the service.
var service = new CalendarService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Calendar API Sample",
});
Event myEvent = new Event
{
Summary = "Appointment",
Location = "Somewhere",
Start = new EventDateTime()
{
DateTime = new DateTime(2014, 6, 2, 10, 0, 0),
TimeZone = "America/Los_Angeles"
},
End = new EventDateTime()
{
DateTime = new DateTime(2014, 6, 2, 10, 30, 0),
TimeZone = "America/Los_Angeles"
},
Recurrence = new String[] { "RRULE:FREQ=WEEKLY;BYDAY=MO" },Attendees = new List<EventAttendee>(){new EventAttendee() { Email = email } }
};
Event recurringEvent = service.Events.Insert(myEvent, "primary").Execute();
}

I have resolved issue my self.Problem was I have put type as "Web Application" Instead of "other".. After I changed it to type as "other" It worked.

Related

How to display IdentityServer endpoints in SwaggerUI with Swashbucke

I have an ASPNET Core 6 service which uses Duende IdentityServer 6, which includes several endpoints such as /connect/token and /connect/authorize. I need these endpoints to show up in my Swagger UI page, however I cannot find a way to get them to show up.
Here is my AddSwaggerGen
builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "API", Version = "v1" });
c.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
{
Type = SecuritySchemeType.OAuth2,
Flows = new OpenApiOAuthFlows
{
ClientCredentials = new OpenApiOAuthFlow
{
AuthorizationUrl =
new Uri($"{builder.Configuration.GetSection("BaseUri").Value}connect/authorize",
UriKind.RelativeOrAbsolute),
TokenUrl = new Uri($"{builder.Configuration.GetSection("BaseUri").Value}connect/token",
UriKind.RelativeOrAbsolute),
Scopes = new Dictionary<string, string>
{
{ Constants.Api.ScopeName, "Base level access to API" }
}
}
}
});
c.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "oauth2" },
In = ParameterLocation.Cookie
},
new string[] { }
}
});
});
And I am just using the basic app.AddSwagger() and app.AddSwaggerUI()
As far as my research has shown, CodingMytra is correct. IdentityServer endpoints must be added manually to the Swagger document.

error:invalid_scope - IdentityServer Flow.ClientCredential

I'm having a Client in my IdentityServer3
new Client
{
ClientName = "Client Credentials Flow Client",
Enabled = true,
ClientId = "clientcredentials.reference",
Flow = Flows.ClientCredentials,
ClientSecrets = new List<Secret>
{
new Secret("secret".Sha256()),
},
AllowedScopes = new List<string>()
{
"read",
"write"
}
}
I hosted the Token Service in my local IIS and I tried to ping the Token using Postman, but it given an error {"error":"invalid_scope"}
Host URL:
https://localhost:5775/core/connect/token
Header:
Content-Type:application/x-www-form-urlencoded
Body:
grant_type=client_credentials
&cliend_id=clientcredentials.reference
&client_secret=secret
Note: I'm using pure IdentityServer3 package not Thinktecture
Check the Scopes "read" and "write" in Scopes declaration
new Scope
{
Name = "read",
DisplayName = "Read data",
Type = ScopeType.Resource,
Emphasize = false,
ScopeSecrets = new List<Secret>
{
new Secret("secret".Sha256())
}
},
new Scope
{
Name = "write",
DisplayName = "Write data",
Type = ScopeType.Resource,
Emphasize = true,
ScopeSecrets = new List<Secret>
{
new Secret("secret".Sha256())
}
}
I think its missed... Check it once...

IdentityServer 3 and ASP.NET Identity: how to get user information

I'm using IdentityServer 3 with ASP.NET Identity as its user store. I have followed this article to set up IdentityServer and my client is an ASP MVC web application. I'm able to login from my client, but I don't understand how to get user information on the client side. On the server side Im using:
var scopes = new Scope[]
{
StandardScopes.OpenId,
StandardScopes.Email,
new Scope
{
Name = "roles",
Claims = new List<ScopeClaim>
{
new ScopeClaim("role")
}
}
};
var clients = new Client[]
{
new Client
{
ClientId = "mvc-demo",
ClientName = "MVC Demo Client",
Flow = Flows.Implicit,
RedirectUris = new List<string>
{
"http://localhost:16652/"
},
AllowedScopes = new List<string>
{
"openid", "email", "roles"
}
}
};
var factory = new IdentityServerServiceFactory().Configure(connectionString);
factory.UseInMemoryClients(clients);
factory.UseInMemoryScopes(scopes);
And on the client side:
app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
{
AuthenticationType = "oidc",
SignInAsAuthenticationType = "cookies",
Authority = "https://localhost:44305/",
ClientId = "mvc-demo",
RedirectUri = "http://localhost:16652/",
ResponseType = "id_token token",
Scope = "openid email roles",
Notifications = new OpenIdConnectAuthenticationNotifications
{
SecurityTokenValidated = n =>
{
var id = n.AuthenticationTicket.Identity;
var email = id.FindFirst(Constants.ClaimTypes.Email);
var roles = id.FindAll(Constants.ClaimTypes.Role);
// create new identity and set name and role claim type
var nid = new ClaimsIdentity(
id.AuthenticationType,
Constants.ClaimTypes.Email,
Constants.ClaimTypes.Role);
nid.AddClaim(email);
nid.AddClaims(roles);
// add some other app specific claim
//nid.AddClaim(new Claim("app_specific", "some data"));
n.AuthenticationTicket = new AuthenticationTicket(
nid,
n.AuthenticationTicket.Properties);
return Task.FromResult(0);
}
}
But I cant get the information about users email for example.
I managed to send claims to my client application this way:
var scopes = new Scope[]
{
StandardScopes.OpenId,
new Scope
{
Name = "roles",
Type = ScopeType.Identity,
Claims = new List<ScopeClaim>
{
new ScopeClaim("role")
}
},
new Scope
{
Name = "email",
Type = ScopeType.Identity,
Claims = new List<ScopeClaim>
{
new ScopeClaim(Constants.ClaimTypes.Email)
}
}
};
var clients = new Client[]
{
new Client
{
ClientId = "mvc-demo",
ClientName = "MVC Demo Client",
Flow = Flows.Implicit,
RedirectUris = new List<string>
{
"http://localhost:16652/"
},
AllowedScopes = new List<string>
{
"openid", "email", "roles"
}
}
};
And on the client side, I needed to turn off claims transformation, to fetch them correctly, like this(in OWIN startup class):
AntiForgeryConfig.UniqueClaimTypeIdentifier = Constants.ClaimTypes.Subject;
JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary<string, string>();

Can't get Seeding to Work EF Code First

I have a couple of related entities and I am trying to seed the database with some dummy data. Here is my seed code:
public class EventInitializer : DropCreateDatabaseAlways<BSContext>
{
protected override void Seed(BSContext context)
{
var authors = new List<Author>
{
new Author { Name = "Christina Gabbitas" },
new Author { Name = "Gemma King" },
new Author { Name = "Gemma Collins"},
new Author { Name = "Billy Hayes" },
new Author { Name = "Jodi Picoult" },
new Author { Name = "John Whaite" }
};
authors.ForEach(a => context.Authors.Add(a));
context.SaveChanges();
var events = new List<Event>
{
new Event { Authors = new List<Author> { context.Authors.Find(0) }, Book = "Felicity Fly", Info = "Christina Gabbitas will be signing copies of her new book, Felicity Fly. Books should be bought from WHSmith. Proof of purchase may be necessary", Start = new DateTime(2013, 05, 25, 10, 30, 00), Url = "http://www.whsmith.co.uk/Support/InStoreSignings.aspx", Location = new Location { Name = "WHSmith Brent Cross", Address = "Brent Cross Shopping Centre", City = "London", County = "", PostCode = "NW4 3FB", Telephone = 02082024226 } },
new Event { Authors = new List<Author> { context.Authors.Find(1) }, Book = "Haunted Spalding", Info = "Gemma King will be signing copies of her new book. Books should be bought from WHSmith. Proof of purchase may be necessary", Start = new DateTime(2013, 03, 31, 10, 00, 00), Url = "http://www.whsmith.co.uk/Support/InStoreSignings.aspx", Location = new Location { Name = "WHSmith Spalding", Address = "6-7 Hall Place", City = "Spalding", County = "Lincolnshire", PostCode = "PE11 1SA", Telephone = 01775768666 } },
new Event { Authors = new List<Author> { context.Authors.Find(3) }, Book = "Midnight Express", Info = "Billy Hayes will be signing copies of his books. Books should be bought from WHSmith. Proof of purchase may be necessary", Start = new DateTime(2013, 04, 13, 13, 00, 00), Url = "http://www.whsmith.co.uk/Support/InStoreSignings.aspx", Location = new Location { Name = "WHSmith Birmingham", Address = "29 Union Street", City = "Birmingham", County = "West Midlands", PostCode = "B2 4LR", Telephone = 01216313303 } }
};
events.ForEach(e => context.Events.Add(e));
context.SaveChanges();
}
}
The seed code above sits in a separate project along with all my entities. I did this to keep my domain model totally separate from my web application. Of course I have references in my controllers to access the entities.
I've used EF Code First before, but this time it isn't working for me! When I go to access the data like so in my controller (ASP.NET MVC application), I get 0 results.
public ActionResult Index()
{
ViewBag.Message = "Move around the map to find events near you.";
var model = new IndexVM();
using(var context = new BSContext())
{
model.Events = (List<Event>)context.Events.ToList();
}
return View(model);
}
I am using EF (v4.0.30319) on Windows 8 64x Pro with Visual Studio 2012. To make matters worse, I can't even debug! My breakpoint is never hit when I try to run in debug mode! Here is my Web.config for the web project.
You need to call Database.SetInitializer like this:
Database.SetInitializer<BSContext>( new EventInitializer() );

Why isn't my database being created in ASP.NET MVC4 with EF CodeFirst

I've been following along with a tutorial by Julie Lerman about using EF CodeFirst to generate the database from code. I'm using MVC4 and working with the default controllers. All I want to do is generate the database. However, in her tutorial, she's working with a console application and calling a create_blog method in her Main function. The create_blog function does the work of creating the database as the name suggests.
In my Global.asax, I have this:
Database.SetInitializer(new CIT.Models.SampleData());
This is my SampleData class:
public class SampleData : CreateDatabaseIfNotExists<Context>
{
protected override void Seed(Context context)
{
base.Seed(context);
new List<Software> {
new Software { Title = "Adobe Creative Suite", Version = "CS6", SerialNumber = "1234634543", Platform = "Mac", Notes = "Macs rock!", PurchaseDate = "2012-12-04", Suite = true, SubscriptionEndDate = null, SeatCount = 4, SoftwareTypes = new List<SoftwareType> { new SoftwareType { Type="Suite" }}, Locations = new List<Location> { new Location { LocationName = "Paradise" }}, Publishers = new List<SoftwarePublisher> { new SoftwarePublisher { Publisher = "Adobe" }}},
new Software { Title = "Apple iLife", Version = "2012", SerialNumber = "123463423453", Platform = "Mac", Notes = "Macs still rock!", PurchaseDate = "2012-11-04", Suite = true, SubscriptionEndDate = null, SeatCount = 4, SoftwareTypes = new List<SoftwareType> { new SoftwareType { Type="Suite" }}, Locations = new List<Location> { new Location { LocationName = "81st Street" }}, Publishers = new List<SoftwarePublisher> { new SoftwarePublisher { Publisher = "Apple" }}},
new Software { Title = "Microsoft Office", Version = "2012", SerialNumber = "12346231434543", Platform = "PC", Notes = "Macs really rock!", PurchaseDate = "2011-12-04", Suite = true, SubscriptionEndDate = null, SeatCount = 4, SoftwareTypes = new List<SoftwareType> { new SoftwareType { Type="Suite" }}, Locations = new List<Location> { new Location { LocationName = "Paradise" }}, Publishers = new List<SoftwarePublisher> { new SoftwarePublisher { Publisher = "Microsoft" }}}
}.ForEach(s => context.Software.Add(s));
}
}
I get no errors when I compile. I just get no database. I looked in my App_Data and all that's there is the default database. I have a dbContext that is getting called because when I had errors in it, they pointed to that file. Do I need to have some kind of create method that is called when the site first compiles?
SetInitializer only sets the initializer strategy and the strategy is executed the first time you access the database. Try adding the following after calling SetInitializer
using (var context = new Context()) { context.Database.Initialize(true); }

Resources