54207

How to get client id and a client secret from MVC5 in OAuth2?

Question:

I am implementing OAuth2 authentication in my MVC 5 application, so I can use it in my Android app. But I am not sure how it all goes, because I never before used Oauth2 or any token authentication.

So far I implemented folowing code in MVC:

OwinContextExtensions.cs

public static class OwinContextExtensions { public static string GetUserId(this IOwinContext ctx) { var result = "-1"; var claim = ctx.Authentication.User.Claims.FirstOrDefault(c => c.Type == "UserID"); if (claim != null) { result = claim.Value; } return result; } }

Startup.Auth.cs

public partial class Startup { public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; } static Startup() { OAuthOptions = new OAuthAuthorizationServerOptions { TokenEndpointPath = new PathString("/token"), Provider = new OAuthAppProvider(), AccessTokenExpireTimeSpan = TimeSpan.FromDays(2), AllowInsecureHttp = true }; } public void ConfigureAuth(IAppBuilder app) { app.UseOAuthBearerTokens(OAuthOptions); } }

OAuthAppProvider.cs

public class OAuthAppProvider : OAuthAuthorizationServerProvider { private ProtokolEntities db = new ProtokolEntities(); public IFormsAuthenticationService FormsService { get; set; } public IMembershipService MembershipService { get; set; } public override Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { if (MembershipService == null) { MembershipService = new AccountMembershipService(); } return Task.Factory.StartNew(() => { var username = context.UserName; var password = context.Password; var userID = db.aspnet_Users.Where(x => x.UserName == username).SingleOrDefault().UserId.ToString(); if (MembershipService.ValidateUser(username, password)) { var claims = new List<Claim>() { new Claim(ClaimTypes.Name, username), new Claim("UserID", userID) }; ClaimsIdentity oAutIdentity = new ClaimsIdentity(claims, Startup.OAuthOptions.AuthenticationType); context.Validated(new AuthenticationTicket(oAutIdentity, new AuthenticationProperties() { })); } else { context.SetError("invalid_grant", "Error"); } }); } public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context) { if (context.ClientId == null) { context.Validated(); } return Task.FromResult<object>(null); } }

Startup.cs.cs

[assembly: OwinStartup(typeof(PageOffice.Startup))] namespace PageOffice { public partial class Startup { public void Configuration(IAppBuilder app) { app.MapSignalR(); ConfigureAuth(app); } } }

When I open Postman and use POST method on <a href="http://localhost:1076/token" rel="nofollow">http://localhost:1076/token</a>, I open Body -> raw and write

<blockquote>

grant_type=password&password=mypassword&username=myusername

</blockquote>

After that I get this as a result:

{ "access_token": "QmmWSh4OZPfC8uv-jyzFzZx1KP05T8b09QlPP3Cy-_Zr9qvWtzWpxNTXOhc4U387N6VHNCnIPklgTEk8CISMyXlcsWAz7MxlRN8qI_Ajg8gjEphHUS1SrO0uDRG2XRqtX1gvTVupym_1xtsdjlwj2VXoc6ySvR0ihb2YjuXnSd4CNgKKaMBQLb1w8P1XB13jc4Pc5tump4-Y4dYn3A5hpvtc9fqpgVAUjZFdiJ_HXMiIpgmqdIFim0Ty8oRZolzpm3RSMPRV6ZIpZBqHG1A2kcdWN-52ZkHuL4_7U743vW0", "token_type": "bearer", "expires_in": 172799 }

How do I find this "<strong>client id</strong>" and a "<strong>client secret</strong>" paremeters? Also I don't really understand how would I use this access_token in android, would the explanation on <a href="https://medium.com/@android2ee/oauth-2-on-android-principles-using-google-apis-afb5cc12d935" rel="nofollow">this</a> tutorial be enough?

Thanks for reading and sorry for this much code :)

Answer1:

There is an RFC about <a href="https://tools.ietf.org/html/draft-ietf-oauth-native-apps-12" rel="nofollow">OAuth2 for native applications</a>. It recommends using the Authorization Code Grant Flow, but without a client secret, because you cannot keep the secret safe in the application binary file.

The Resource Owner Password Credentials flow you are now using (see <a href="https://tools.ietf.org/html/rfc6749#section-1.3.3" rel="nofollow">OAuth2 RFC</a>), should be used only in rare situation when the resource owners can completely trust the application, because the application must know their passwords.

You get or specify the client ID and secret when you register you application (client) at the OAuth2 provider.

The tutorial you linked seems to discuss OAuth version 1, not 2.

Recommend

  • How can I get yesterday's date without using Calendar in Java and without a timestamp just the
  • How to call go function from java?
  • Object reference error using Partial Views
  • How to copy CAlayer object in iOS?
  • BigRquery will not connect and the error message is blank
  • How to reuse MPI_Scatter and MPI_Gather in a loop
  • How to import FXG to a Shape?
  • display all elements in a nested cell array (with character entries)
  • Add clickable imageView in expandableListView
  • Fetch friend list from Google Plus
  • java.io.FileNotFoundException: No such file or directory Error
  • Detect whether custom keyboard is currently active from keyboard's container application
  • Laravel edit existing pdf
  • Can we create an apk without an user interface in android
  • How To Tell If User Is At A Specific Location?
  • find_in_batches does not use given order but uses id asc
  • Apache Flink: Where do State Backends keep the state?
  • how to find the co-ordinates(lati&long) of a selected location in objective c
  • Pointer to an array of ints
  • Updating a 'master' JSON object by adding data to a subobject
  • Which built in AudioUnit can resample audio?
  • How to run python script in Rstudio
  • Swing vertical Navigation Menu
  • AMD vs NVIDIA. How do they differentiate in terms of support of OpenCL?
  • ASP.Net Web Application deployment steps
  • Metro Flyouts with MVVM
  • Phonegap Filetransfer Upload image to Webservice
  • Java, How to refresh JTable in one frame from another frame
  • PDF Add Text and Flatten
  • Simulating a FULL OUTER JOIN in Access
  • Use animate() with series of levelplots in R raster
  • Android: Check if object is present in database using Room and RxJava
  • candlestick plot from pandas dataframe, replace index by dates
  • How to change the default browser in visual studio code latest released?
  • Get method parameters with specific annotation in aspect in scala using java reflection
  • Print a Form at higher dpi than screen resolution
  • Insert statement not working using execute(array()) of PDO Extension
  • Making query to find nearest multiple(Lat,Long) from the single(Lat,Long)
  • Slick: How can I combine a SQL LIKE statement with a SQL IN statement
  • How to encrypt Connectionstring written in web.config from codebehind?