紧接着我们在Api目录下创建OAuthOptions类用来配置OAuth认证。
public class OAuthOptions { /// <summary> /// Gets or sets the server options. /// </summary> /// <value>The server options.</value> private static OAuthAuthorizationServerOptions _serverOptions; /// <summary> /// Creates the server options. /// </summary> /// <returns>OAuthAuthorizationServerOptions.</returns> public static OAuthAuthorizationServerOptions CreateServerOptions() { if (_serverOptions == null) { var provider = IocManager.Instance.Resolve<SimpleAuthorizationServerProvider>(); var refreshTokenProvider = IocManager.Instance.Resolve<SimpleRefreshTokenProvider>(); _serverOptions = new OAuthAuthorizationServerOptions { TokenEndpointPath = new PathString("/oauth/token"), Provider = provider, RefreshTokenProvider = refreshTokenProvider, AccessTokenExpireTimeSpan = TimeSpan.FromSeconds(30), AllowInsecureHttp = true }; } return _serverOptions; } }从中我们可以看出,主要配置了以下几个属性:
创建上面三个类之后,我们需要回到Web项目的Startup类中,配置使用集成的OAuth2.0,代码如下:
public void Configuration(IAppBuilder app) { //第一步:配置跨域访问 app.UseCors(CorsOptions.AllowAll); app.UseOAuthBearerAuthentication(AccountController.OAuthBearerOptions); //第二步:使用OAuth密码认证模式 app.UseOAuthAuthorizationServer(OAuthOptions.CreateServerOptions()); //第三步:使用Abp app.UseAbp(); //省略其他代码 }其中配置跨越访问时,我们需要安装Microsoft.Owin.CorsNuget包。
至此,Abp集成OAuth的工作完成了。
4.2. 申请OAuth token我们在Abp集成OAuth配置的申请token的路由是/oauth/token,所以我们将用户凭证post到这个路由即可申请token:
public async Task<string> GetOAuth2Token() { Uri uri = new Uri(baseUrl + oAuthTokenUrl); var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.None }; using (var client = new HttpClient(handler)) { client.BaseAddress = uri; client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); var content = new FormUrlEncodedContent(new Dictionary<string, string>() { {"grant_type", "password"}, {"username", user }, {"password", pwd }, {"client_id", "app" }, {"client_secret", "app"}, }); //获取token保存到cookie,并设置token的过期日期 var result = await client.PostAsync(uri, content); string tokenResult = await result.Content.ReadAsStringAsync(); var tokenObj = (JObject)JsonConvert.DeserializeObject(tokenResult); string token = tokenObj["access_token"].ToString(); string refreshToken = tokenObj["refresh_token"].ToString(); long expires = Convert.ToInt64(tokenObj["expires_in"]); this.Response.SetCookie(new HttpCookie("access_token", token)); this.Response.SetCookie(new HttpCookie("refresh_token", refreshToken)); this.Response.Cookies["access_token"].Expires = Clock.Now.AddSeconds(expires); return tokenResult; } }