[ASP. NET] Implementing OAuth and owinoauth under OWIN with Web APIs
OAuth (Open Authorization)
It provides a secure, open, and simple standard for user resource authorization. Unlike the previous authorization method, OAuth does not allow a third party to access user account information (such as user name and password ), that is, a third party can apply for authorization to the user's resources without using the user name and password. Therefore, OAuth is secure.
This section contains the following contents:
- WebAPI SelfHost under Owin
- Create an AccessToken
- Use AccessToken
WebAPI SelfHost under Owin
1. Create a console project (in fact, all class libraries are supported) ApiServer
Nuget reference:
Install-Package Microsoft. AspNet. WebApi. OwinSelfHost
Or reference the following three
Install-Package Microsoft. AspNet. WebApi. Owin (using WebApi as middleware)
Install-Package Microsoft. Owin. Hosting (the Hosting interface uses HttpListener as the Server by default)
Install-Package Microsoft. Owin. Host. HttpListener (default Server implementation)
2. Add the Startup class
public void Configuration(IAppBuilder app)
{
//For more information on how to configure an application, visit http://go.microsoft.com/fwlink/? LINKID = 316888
ApiConfig(app);
}
private static void ApiConfig(IAppBuilder app)
{
var config = new HttpConfiguration();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional , action = RouteParameter.Optional }
);
app.UseWebApi(config);
}
How to associate owin with startup methods can be found in my blog:
[asp.net] next generation asp.net development specification: win
3. Create an API controller
public class ValuesController : ApiController
{
public string Get()
{
return "Never、C";
}
}
4. Main method start
static void Main(string[] args)
{
const string url = "http://localhost:1234/";
using (WebApp.Start<Startup>(url))
{
Console.writeline ("open successfully");
Console.ReadLine();
}
}
5. Browser access
Create accesstoken
Based on the above win web API, start to implement OAuth
Nuget:
Install package microsoft.owin.security.oauth (implementation of OAuth of owin)
Using OAuth will require owin to use the useoauthbearertokens authentication method, so reference
Install-Package Microsoft.AspNet.Identity.Owin
1. Add a middleware configuration in startup
private static void OAuthConfig(IAppBuilder app)
{
var OAuthOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/token"),
Provider = new OTWAuthorizationServerProvider(),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
AllowInsecureHttp = true,
}
app.UseOAuthBearerTokens(OAuthOptions);
}
And set the web API to use OAuth
Config. Filters. Add (New hostauthenticationfilter (oautdefaults. Authenticationtype)); / / added configuration
app.UseWebApi(config);
2. Customized provider
public class OTWAuthorizationServerProvider : OAuthAuthorizationServerProvider
{
//1. Verify customer
public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
//Here you can judge the client and user
//this.ClientId = clientId;
//this.IsValidated = true;
//this.HasError = false;
Context. Validated ("custom ClientID");
return base.ValidateClientAuthentication(context);
}
//Authorized customers
public override Task GrantClientCredentials(OAuthGrantClientCredentialsContext context)
{
var ticket = new AuthenticationTicket(new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, "Never、C") }, context.Options.AuthenticationType), null);
//this.Ticket = ticket;
//this.IsValidated = true;
//this.HasError = false;
context.Validated(ticket);
return base.GrantClientCredentials(context);
}
}
3. Use the client to call our (it is not recommended to use unit test, create a new console project here)
static void Main(string[] args)
{
const string url = "http://localhost:1234/";
var client = new HttpClient();
var rst = client.PostAsync(url + "token", new StringContent("grant_type=client_credentials")).Result.Content.ReadAsStringAsync().Result;
Console.WriteLine(rst);
}
4. Start the server first, then the client
Use accesstoken
1. Valuescontroller add attribute authorize
[Authorize]
public class ValuesController : ApiController
{
public string Get()
{
return User.Identity.Name;
}
}
Visit will return
{"Response status code does not indicate success: 401 (Unauthorized)."}
2. Client reference
Install-Package Newtonsoft.Json -Version 7.0.1
3. Modify the main method with token
class Program
{
static void Main(string[] args)
{
const string url = "http://localhost:1234/";
var client = new HttpClient();
var rst = client.PostAsync(url + "token", new StringContent("grant_type=client_credentials")).Result.Content.ReadAsStringAsync().Result;
var obj = JsonConvert.DeserializeObject<Token>(rst);
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", obj.AccessToken);
rst = client.GetStringAsync(url + "api/values").Result;
Console.WriteLine(rst);
Console.ReadLine();
}
}
public class Token
{
[JsonProperty("Access_Token")]
public string AccessToken { get; set; }
}
4. Start the server first, then the client
extend
In fact, OAuth can also be implemented by itself. Its essence is to generate an encrypted unique string
The implementation of OAuth also includes dotnetopenauth and thinking identity server
Address: http://neverc.cnblogs.com/p/4970996.html
Reference resources:
http://bitoftech.net/2014/06/01/token-based-authentication-asp-net-web-api-2-owin-asp-net-identity/
http://www.cnblogs.com/dudu/p/4569857.html