WebAPI 2에서 CORS 인증을 만드는 방법은 무엇입니까?
시나리오는 간단합니다. 액세스 토큰을 검색하려면 API 서버와 다른 다른 서버에서 로그인해야합니다.
Microsoft.Owin.Cors
API 서버에 패키지를 설치했습니다 . 에서 Startup.Auth.cs
파일, 아래 public void ConfigureAuth(IAppBuilder app)
, 나는 추가
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
에서 WebApiConfig.cs
, 아래 public static void Register(HttpConfiguration config)
, 나는이 라인에 추가 :
// Cors
var cors = new EnableCorsAttribute("*", "*", "GET, POST, OPTIONS");
config.EnableCors(cors);
그 밖에 무엇을 변경해야합니까?
내가 찾은 것 좀 봐!
내부에 사용자 정의 헤더를 추가하십시오 <system.webServer>
.
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="GET, POST, OPTIONS, PUT, DELETE" />
</customHeaders>
</httpProtocol>
그런 다음 CORS 인증을 수행 할 수 있습니다.
AngularJS 기반 웹 클라이언트에 대해 설정하는 데 많은 시행 착오가있었습니다.
나를 위해 아래 접근 방식은 ASP.NET WebApi 2.2 및 OAuth 기반 서비스에서 작동합니다.
Microsoft.AspNet.WebApi.Cors
너겟 패키지를 설치 하십시오.Microsoft.Owin.Cors
너겟 패키지를 설치 하십시오.- Startup.cs 파일 에서
config.EnableCors(new EnableCorsAttribute("*", "*", "GET, POST, OPTIONS, PUT, DELETE"));
위의WebApiConfig.Register(config);
줄에 추가 하십시오. - 추가
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
받는 Startup.Auth.cs의 파일. 이것은 전화하기 전에해야합니다.IAppBuilder.UseWebApi
- Blaise가 수행 한 모든 xml 설정을 제거합니다.
여기 stackoverflow 또는 블로그 기사 에서 많은 설정 변형 및 조합을 발견했습니다 . 따라서 Blaise의 접근 방식은 잘못되거나 잘못되지 않을 수 있습니다. 제가 생각하는 또 다른 설정일뿐입니다.
많은 시간 동안 검색하고 이것에 대한 많은 다른 솔루션을 살펴본 후 아래에 따라 작동하도록 관리했습니다.
이런 일이 발생하는 데에는 여러 가지 이유가 있습니다. CORS를 잘못된 위치에서 활성화했거나 두 번 활성화하거나 전혀 활성화하지 않았을 가능성이 높습니다.
웹 API 및 Owin 토큰 끝점을 사용하는 경우 웹 API 메서드에서 CORS에 대한 모든 참조를 제거하고 올바른 owin 메서드를 추가해야합니다. 웹 API cors는 토큰 끝점에서 작동하지 않지만 Owin cors는 두 웹 모두에서 작동하기 때문입니다. API 및 토큰 인증 끝점이므로 시작하겠습니다.
Owin Cors 패키지가 설치되어 있는지 확인하십시오. eg.config.EnableCors (); WebAPIconfig.cs 파일에서
startup.cs 파일로 이동하여 다른 구성이 실행되기 전에 Owin Cors를 실행했는지 확인하십시오.
app.UseCors (Microsoft.Owin.Cors.CorsOptions.AllowAll); ConfigureAuth (앱);
여전히 문제가있는 경우 : Startup.Auth.cs로 이동하여 ConfigureAuth 메서드에 다음이 있는지 확인합니다 (startup.cs 파일이 올바른 경우에는 필요하지 않음).
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
web.config
<appSettings>
<add key="cors:Origins" value="*" />
<add key="cors:Headers" value="*" />
<add key="cors:Methods" value="GET, POST, OPTIONS, PUT, DELETE" />
</appSettings>
Startup.cs
var appSettings = WebConfigurationManager.AppSettings;
// If CORS settings are present in Web.config
if (!string.IsNullOrWhiteSpace(appSettings["cors:Origins"]))
{
// Load CORS settings from Web.config
var corsPolicy = new EnableCorsAttribute(
appSettings["cors:Origins"],
appSettings["cors:Headers"],
appSettings["cors:Methods"]);
// Enable CORS for ASP.NET Identity
app.UseCors(new CorsOptions
{
PolicyProvider = new CorsPolicyProvider
{
PolicyResolver = request =>
request.Path.Value == "/token" ?
corsPolicy.GetCorsPolicyAsync(null, CancellationToken.None) :
Task.FromResult<CorsPolicy>(null)
}
});
// Enable CORS for Web API
config.EnableCors(corsPolicy);
}
참고 : app.UserCors(...)
ASP.NET ID를 구성하기 전에 호출해야합니다.
출처 : ASP.NET 웹 애플리케이션 스타터 키트 (ASP.NET 웹 API, ID, SignalR)
Youngjae의 답변에 대해 자세히 설명하기 위해 http://bitoftech.net/2014/06/01/token-based-authentication-asp-net-web- 에서 Web API로 OWIN을 설정하고 CORS를 활성화하는 방법에 대한 훌륭한 자습서가 있습니다. api-2-owin-asp-net-identity /
다음 명령을 사용하여 CORS 용 NuGet 패키지를 추가 할 수 있습니다.
Install-Package Microsoft.Owin.Cors -Version 2.1.0
그런 다음 추가
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
Startup.cs의 Configuration 메서드에 다음과 같이 표시됩니다.
public void Configuration(IAppBuilder app)
{
HttpConfiguration config = new HttpConfiguration();
ConfigureOAuth(app);
WebApiConfig.Register(config);
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
app.UseWebApi(config);
}
나에 대한 대답은
Bearer Token에 대한 Web Api 2 Preflight CORS 요청
특히 OAuthAuthorizationServerProvider.GrantResourceOwnerCredentials 구현을 사용하는 / Token 요청은 헤더를 다시 추가했습니다. 다른 OWIN 구성 전에 OWIN CORS 항목을 추가하고 해당 링크에 따라 GrantResourceOwnerCredentials에서 헤더를 제거하십시오. 행운을 빕니다.
제 경험을 공유하고 싶습니다. 나는 하루의 절반을 머리를 두드리며 작동하도록 노력했습니다. 나는 수많은 기사와 질문을 읽었고 결국 무엇이 잘못되었는지 알아 냈습니다.
라인
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
Startup
클래스 Configuration
메서드 에서 첫 번째가 아니 었습니다 . 내가 그것을 맨 위로 옮겼을 때-모든 것이 마술처럼 작동하기 시작했습니다.
그리고에는 사용자 정의 헤더 web.config
또는 config.EnableCors(corsPolicy);
다른 사람 또는 아무것도 필요 없었다.
누군가가 시간을 절약하는 데 도움이되기를 바랍니다.
여기에서 다양한 범위에서 CORS를 활성화하는 여러 방법을 찾을 수 있습니다. http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api
어쨌든 동일한 문제가 있었고 다른 방법으로 헤더를 추가해도 완전한 솔루션을 얻지 못했습니다.
IIS는 반대를 지정하지 않으면 CORS 웹 앱 구성을 재정의하는 처리기를 사용한다는 것을 알았습니다.
필자의 경우 응용 프로그램의 기본 Web.config에 다음 구성을 추가하여 IIS 처리기 사용을 제거해야했습니다.
<system.webServer>
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
이 구성은 유형에 따라 새 프로젝트를 만들 때 기본적으로 설정 될 수 있지만 처음부터 시작하는 경우이 구성을 추가해야 할 수 있습니다.
Adding customer Headers might not give you as much freedom in customize your security needs. It opens up all other part of the api to the world. The following code only does that for "token", and controller other part of api should be done via EableCors annotation.
public void ConfigureAuth(IAppBuilder app)
{
//other stuff
app.Use(async (context, next) =>
{
IOwinRequest req = context.Request;
IOwinResponse res = context.Response;
if (req.Path.StartsWithSegments(new PathString("/Token")))
{
var origin = req.Headers.Get("Origin");
if (!string.IsNullOrEmpty(origin))
{
res.Headers.Set("Access-Control-Allow-Origin", origin);
}
if (req.Method == "OPTIONS")
{
res.StatusCode = 200;
res.Headers.AppendCommaSeparatedValues("Access-Control- Allow-Methods", "GET", "POST");
res.Headers.AppendCommaSeparatedValues("Access-Control- Allow-Headers", "authorization", "content-type");
return;
}
}
await next();
});
//other stuff
}
To enable Cors, follow the instruction here.
When using OWIN middleware to handle CORS, we do not need to add headers on the WebAPIConfig or the web.config file. Yes, adding the headers on the web.config file does work when you want public access, but if you need to limit the access based on a whitelist (domains), then allowing All access is no longer what you would like to do.
With OWINS, we can handle this by implementing this handler:
OAuthAuthorizationServerProvider.MatchEndpoint
With this handler, we can detect the request method (OPTIONS, POST...) and if the request should be treated as an Authorize or Token endpoint. This is the area where logic can be added to check the Origin header (request) and validate if this domain should be allowed by adding the response header Access-Control-Allow-Origin.
string origin = context.Request.Headers.Get("Origin");
var found = IsDomainAllowed(origin);
if (found){
context.Response.Headers.Add("Access-Control-Allow-Origin",
new string[] { origin });
}
For more background on this, look at this link: http://www.ozkary.com/2016/04/web-api-owin-cors-handling-no-access.html
Complete Soluction. You just need change some files, works for me.
Global.ascx
public class WebApiApplication : System.Web.HttpApplication {
protected void Application_Start()
{
WebApiConfig.Register(GlobalConfiguration.Configuration);
} }
WebApiConfig.cs
All the request has call this code.
public static class WebApiConfig {
public static void Register(HttpConfiguration config)
{
EnableCrossSiteRequests(config);
AddRoutes(config);
}
private static void AddRoutes(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "Default",
routeTemplate: "api/{controller}/"
);
}
private static void EnableCrossSiteRequests(HttpConfiguration config)
{
var cors = new EnableCorsAttribute(
origins: "*",
headers: "*",
methods: "*");
config.EnableCors(cors);
} }
Some Controller
Nothing to change.
Web.config
You need add handlers in you web.config
<configuration>
<system.webServer>
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
</configuration>
참고URL : https://stackoverflow.com/questions/20079813/how-to-make-cors-authentication-in-webapi-2
'program tip' 카테고리의 다른 글
jquery를 사용하여 통화 형식을 올바르게 지정하려면 어떻게해야합니까? (0) | 2020.10.28 |
---|---|
이름 패턴을 가져올 수 없습니다. (0) | 2020.10.28 |
JavaScript에서 Reflect 객체는 무엇을합니까? (0) | 2020.10.27 |
Wt C ++ 프레임 워크를 사용한 경험이 있습니까? (0) | 2020.10.27 |
입력 요소의 Javascript 변경 이벤트가 포커스를 잃을 때만 발생합니다. (0) | 2020.10.27 |