I have created Asp.net WebApi and enable TwitterAuthentication code.
On HomeController.cs used [Authorize] attribute.
Now how can I verify credentials and give access to Authorize Controller without open login box ?
public void ConfigureAuth(IAppBuilder app)
{
// Configure the db context and user manager to use a single instance per request
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
// Enable the application to use a cookie to store information for the signed in user
// and to use a cookie to temporarily store information about a user logging in with a third party login provider
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
// Configure the application for OAuth based flow
PublicClientId = "self";
OAuthOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/Token"),
Provider = new ApplicationOAuthProvider(PublicClientId),
AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
// In production mode set AllowInsecureHttp = false
AllowInsecureHttp = true
};
// Enable the application to use bearer tokens to authenticate users
app.UseOAuthBearerTokens(OAuthOptions);
// Uncomment the following lines to enable logging in with third party login providers
//app.UseMicrosoftAccountAuthentication(
// clientId: "",
// clientSecret: "");
app.UseTwitterAuthentication(
consumerKey: "mykey",
consumerSecret: "mysecret");
}
I have added one application into twitter app - get the consumer key.
and consumer secret.
I do not want a twitter login popup to be opened
for login credentials while authorizing webapi.
Related
I am trying to set up an SSO sign in to a ASP.NET MVC 5 application (.NET 4.8) with OpenID Connect. I'm using Azure Active Directory. The application is a brand new project made for testing purposes, and the only change I introduced to scaffolded code is in Startup.Auth.cs:
// automatically added usings:
using Microsoft.IdentityModel.Tokens;
using Microsoft.Owin.Security.OpenIdConnect;
// in public void ConfigureAuth(IAppBuilder app) method:
app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
{
ClientId = "{ClientId of AAD App}",
ClientSecret = "{Secret generated for the AAD app}",
CallbackPath = new PathString("/signin-microsoft"),
MetadataAddress = "https://login.microsoftonline.com/organizations/v2.0/.well-known/openid-configuration",
TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidIssuer = "https://login.microsoftonline.com/{Directory (tenant) ID}/v2.0"
}
});
If I set ValidateIssuer to false, everything works fine - I manage to sign into the application with my organization email. But as soon as I set it to true, I start getting the following error:
IDX10205: Issuer validation failed. Issuer: '[PII is hidden]'. Did not match: validationParameters.ValidIssuer: '[PII is hidden]' or validationParameters.ValidIssuers: '[PII is hidden]'.
I tried changing the ValidIssuer to all options mentioned in this SO thread, but nothing works. The current ValidIssuer is the URL given in the MetadataAddress above, with concrete Directory (tenant) ID of the registered app.
As far as the registered AAD app goes, I've set both Access tokens (used for implicit flows) and ID tokens (used for implicit and hybrid flows) to true and Supported account types to Accounts in any organizational directory (Any Azure AD directory - Multitenant).
Any idea what I'm not getting here?
It was a bad Tennant ID after all.
I realized it by setting IdentityModelEventSource.ShowPII to true in Startup.Auth.cs, as seen in this answer: https://stackoverflow.com/a/55027625/2975357
I have implemented Single-Sign on in an existing C# Asp.Net MVC 4.5 application and therefore used Owin middleware and OpenIdConnectAuthentication.
The authentication and authorization works fine, but now I have following problem:
I sign in to my application by using AzureAD as identity provider
I sign in to Office365 in another browser tab
I sign out of my application - get redirected to the identity provider and also automatically sign out there
Office365 automatically signs out within the other tab
I do not have configured Single Sign out (so I didn't specified a Logout Url within the App Registration and neither in the configuration code), but I am still signed out of Office365. This is annoying for the customer, as he always uses Outlook365 within the browser.
How can I prevent Office365 from signing out the user automatically.
Here is a simplified code of my configuration of OpenIdConnect:
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
ClientId = clientId,
Authority = authority,
Notifications = new OpenIdConnectAuthenticationNotifications
{
AuthorizationCodeReceived = (context) =>
{
// ... my sign in logic ...
context.OwinContext.Response.Redirect(homeUrl);
return Task.FromResult(0);
},
},
AuthenticationType = OpenIdConnectAuthenticationDefaults.AuthenticationType
});
And here is how I sign out of the application:
context.GetOwinContext().Authentication.SignOut(new AuthenticationProperties { RedirectUri = redirectUrl }, OpenIdConnectAuthenticationDefaults.AuthenticationType);
Is there any way to user both Token based authentication and Windows authentication in a web api application?
We have a "standard" web-api-application using token based (bearer) authentication.
The OAuth-Configuration looks like this:
OAuthOptions = new OAuthAuthorizationServerOptions {
TokenEndpointPath = new PathString("/Token"),
Provider = new ApplicationOAuthProvider(PublicClientId),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
};
app.UseOAuthBearerTokens(OAuthOptions);
Everything works fine. When calling the "/Token"-endpoint you get your token and are authorized.
Now I want to add windows authentication, to enable "signle-sign-on" with the logged in user of the windows-os of the client calling the web-api.
What I did so far:
Changed the web.config and added
<system.web>
<identity impersonate="true" />
<validation validateIntegratedModeConfiguration="false" />
</system.web>
Now every Request is authenticated with the windows user, without using the token process.
So I added anoother provider, to log in with your windows identity and get a token:
app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions {
TokenEndpointPath = new PathString("/IdentityToken"),
Provider = new WindowsIdenityAuthorizationServerProvider(),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
});
The provider should do almost the same as the ApplicationOAuthProvider that generates the token for a request with username and password, except the validation of the password.
Unfortunatly, there is no user/identity set in the request against the "/IdentityToken"-endpoint.
Can anyone help me with this or am I completely on the wrong track?
I have implemented custom asp.net identity with database first approach. I have implemented token based implementation using OWIN.
app.CreatePerOwinContext<OVT_UserEntities>(() => new OVT_UserEntities());
app.CreatePerOwinContext<UserManager<User, int>>(
(IdentityFactoryOptions<UserManager<User, int>> options, IOwinContext context) =>
new UserManager<User, int>(new UserStore(context.Get<OVT_UserEntities>())));
// Enable the application to use bearer tokens to authenticate users
app.UseOAuthBearerTokens(new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/token"),
Provider = new OVTApplicationOAuthProvider(
"self", () => HttpContext.Current.GetOwinContext().GetUserManager<UserManager<User, int>>()),
AuthorizeEndpointPath = new PathString("/api/account/authorize"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
AllowInsecureHttp = true
});
OVT_UserEntities is my custom db context which will validate the entered username with my own database.
now i want to do active directory authentication for organizational users account.
How can i implement both database asp.net identity authentication + active directory implementation in asp.net identity authentcation.
if the user enters his creditentials, first i will check in database ,if it's not available then will go for active directory for further checking. if is avail in AD(active directory) then will redirect some other page by getting some tokens.
any references would be appreciated.
I have a web application. My requirement is that i need to generate oauth2 bearer token on every login. Currently we are using thinktecture to generate token, but this procedure is taking almost 7 seconds to generate token everytime. Is there any way i can generate token without using thinktecture ?
If you have created a new ASP.NET Web Application -> Web API with Individual User Accounts. Have a look at App_Start -> Startup.Auth.cs.
It should contain something like this:
PublicClientId = "self";
OAuthOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/Token"),
Provider = new ApplicationOAuthProvider(PublicClientId),
AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
// In production mode set AllowInsecureHttp = false
AllowInsecureHttp = true
};
// Enable the application to use bearer tokens to authenticate users
app.UseOAuthBearerTokens(OAuthOptions);
This means that you can send a request for an access token, example request:
You can then verify that the access token works:
With this token you can now access all protected resources that the user has access to.
Asp.net default implementation will use DPAPI in your Authorization Server, so it will use the “validationKey” value in machineKey node stored in machine.config file to issue the access token and protect it. The same case applies when you send the access token to your Resource Server, it will use the same machineKey to decrypt the access token and extract the authentication ticket from it.
ASP.NET
If you want to generate a JWT encoded Bearer Token, you should override ISecureDataFormat<AuthenticationTicket>.Protect() Method:
CustomJwtFormat.cs
string symmetricKeyAsBase64 = audience.Base64Secret;
var keyByteArray = TextEncodings.Base64Url.Decode(symmetricKeyAsBase64);
var signingKey = new HmacSigningCredentials(keyByteArray);
var issued = data.Properties.IssuedUtc; var expires = data.Properties.ExpiresUtc;
JwtSecurityToken token = new JwtSecurityToken(_issuer, audienceId, data.Identity.Claims, issued.Value.UtcDateTime,expires.Value.UtcDateTime, signingKey);
var handler = new JwtSecurityTokenHandler();
//serialize the JSON Web Token to a string
var jwt = handler.WriteToken(token);
return jwt;
Add your custom JWT formatter to OAuth Option
OAuthAuthorizationServerOptions OAuthServerOptions = new
OAuthAuthorizationServerOptions()
{
//For Dev enviroment only (on production should be AllowInsecureHttp = false)
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/oauth/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30),
AccessTokenFormat = new CustomJwtFormat("http://localhost:5001")
};
// Generation and validation
app.UseOAuthBearerTokens(OAuthServerOptions);
The app.UseOAuthBearerTokens helper method creates both the token server and the middleware to validate tokens for requests in the same application.
If this is an Authorization server(generate token) , you should use app.UseOAuthAuthorizationServer(OAuthServerOptions) in the last line
ASP.NET Core
Unforturnately, the ASP.NET team simply decided not to port OAuthAuthorizationServerMiddleware to asp.net core: https://github.com/aspnet/Security/issues/83
community-provided, open source authentication options for ASP.NET Core:
AspNet.Security.OpenIdConnect.Server:low-level, protocol-first OpenID Connect server framework for ASP.NET Core and OWIN/Katana.
IdentityServer:OpenID Connect and OAuth 2.0 framework for ASP.NET Core, officially certified by the OpenID Foundation and under governance of the .NET Foundation.
OpenIddict: easy-to-use OpenID Connect server for ASP.NET Core.
I followed below article http://bitoftech.net/2014/06/01/token-based-authentication-asp-net-web-api-2-owin-asp-net-identity/
Downloaded their sourcecode and checked it. They have good example on how to create token.