【发布时间】:2019-08-13 22:48:59
【问题描述】:
我无法访问 web api 上的受保护资源,例如[授权]
使用 OAuth/OWIN ...
我能做什么: 1.生成不记名令牌 2.发送不记名令牌(来自Axios) 3. 我在这个链接上试过这个解决方案:
意思是更新了web.config、startUp、webApiConfig,
我已经有一段时间了。我打电话和 chrome 网络调试器
{"message":"此请求的授权已被拒绝。"}
[Authorize]
[RoutePrefix("api/testV2")]
public class testController : BaseApiController
{
readonly ItestV2Service _service;
//public testController()
//{
//}
public testController(ItestV2Service service)
{
_service = service;
}
然后
启动
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Owin;
using Owin;
using Microsoft.Owin.Security.OAuth;
[assembly: OwinStartup(typeof(testV2.Startup))]
namespace testV2
{
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions { });
ConfigureAuth(app);
}
}
}
网络配置
<appSettings>
<add key="owin:appStartup" value="testV2.Startup" />
</appSettings>
<system.web>
<authentication mode="None" />
<compilation debug="true" targetFramework="4.6.1" />
<httpRuntime targetFramework="4.6.1" />
<machineKey validationKey="750C536CFAEE1375A4FB62025BB841684D463BDB13D375ECE8853121BD03C596FD042C423F47E88CFD1B81ECDE4812FE43DDEF89C6DB699DD9B65DD26462BE44"
decryptionKey="A34768D4D9AA3B309525F0A4AE642B2E8004155FC441827C"
validation="SHA1"
decryption="AES"/>
</system.web>
这是 wedApiconfig
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Web.Http;
using Microsoft.Owin.Security.OAuth;
using Newtonsoft.Json.Serialization;
namespace testV2
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Configure Web API to use only bearer token authentication.
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
// Web API routes
config.MapHttpAttributeRoutes();
var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
这是startAuth up
namespace testV2
{
public partial class Startup
{
public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; }
public static string PublicClientId { get; private set; }
// For more information on configuring authentication, please visit https://go.microsoft.com/fwlink/?LinkId=301864
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);
这是 axios 调用
const getAllVideo = header => {
let url = basePath2;
let config = {
headers: {
"Content-Type": "application/json",
header
},
method: "GET",
withCredentials: true,
crossdomain: true
};
return axios(url, config);
};
【问题讨论】:
标签: asp.net .net asp.net-web-api2 axios