ASP.NET MVC 5 및 WEB API 2에서 oauth2 서버를 구현하는 방법
먼저 프로젝트를 스케치하겠습니다.
인턴쉽을 위해서는 기존 시스템에 기능을 추가해야합니다. OAuth2를 통해 사용자가 권한을 부여한 타사 클라이언트는 AX 웹 서비스의 데이터에 액세스 할 수 있어야합니다. 나는 클라이언트가 전화를 걸고 AX 서비스를 호출 할 수있는 '프록시 웹 서비스'를 만들어야한다는 것을 이해하지만 OAuth2 부분에 대해서는 조금 확신이 없습니다. 대부분의 자습서 및 안내서는 Facebook 또는 Google 로그인에 ASP.NET의 ID를 사용하는 것에 관한 것입니다. 필요하지 않습니다. 기존 자격 증명을 사용해야하므로 고유 한 OAuth2 서비스를 만들어야합니다.
이에 대한 자습서, 안내서 또는 설명을 찾기가 어렵습니다. OAuth2와 수행해야 할 작업을 이해하지만 이전에는 그런 일을 한 적이 없으며 시작하기가 어렵습니다. 내가 찾은 것에 가장 가까운 것은이 github repo link 이지만 솔루션은 빌드되지 않습니다.
내가 염두에 둔 것은 클라이언트 (타사)가 자신을 등록하고 고객 ID를 얻을 수있는 ASP.NET MVC 웹 사이트를 만드는 것입니다. ASP.NET API를 사용하여 필요한 토큰과 매개 변수를 취하는 API를 만들고 Dyn AX 서비스에 액세스하려고했습니다.
이것이 맞습니까? 아니면 완전히 틀렸습니까? 자신 만의 oauth2 서버 / 서비스 구축에 관한 도움이나 링크가 있으면 좋을 것입니다.
Taiseer Joudeh 의 훌륭한 블로그 게시물 에 자세한 단계별 설명이 있습니다.
- 1 부 : ASP.NET Web API 2, Owin 및 Identity를 사용한 토큰 기반 인증
- 2 부 : ASP.NET 웹 API 2, Owin 및 Identity를 사용한 AngularJS 토큰 인증
- 3 부 : ASP .NET Web API 2 및 Owin을 사용하여 AngularJS 앱에서 OAuth 새로 고침 토큰 사용
- 파트 4 : AngularJS 앱에서 Facebook 및 Google을 사용한 ASP.NET Web API 2 외부 로그인
- 5 부 : 리소스 서버에서 OWIN 인증 서버 분리
또한 토큰 부분을 생성하는 방법에 대한 기사를 찾는 데 어려움을 겪었습니다. 나는 하나를 찾지 못했고 내 자신을 썼다. 도움이된다면 :
해야 할 일은 :
- 새로운 웹 애플리케이션 만들기
- 다음 NuGet 패키지를 설치하십시오.
Microsoft.Owin
Microsoft.Owin.Host.SystemWeb
Microsoft.Owin.Security.OAuth
Microsoft.AspNet.Identity.Owin
- OWIN
startup
클래스 추가
그런 다음 index.js
다음 내용 으로 HTML과 JavaScript ( ) 파일을 작성하십시오 .
var loginData = 'grant_type=password&username=test.test@mail.com&password=test123';
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
alert(xmlhttp.responseText);
}
}
xmlhttp.open("POST", "/token", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(loginData);
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript" src="index.js"></script>
</body>
</html>
OWIN startup
클래스에는 다음 내용이 있어야합니다.
using System;
using System.Security.Claims;
using Microsoft.Owin;
using Microsoft.Owin.Security.OAuth;
using OAuth20;
using Owin;
[assembly: OwinStartup(typeof(Startup))]
namespace OAuth20
{
public class Startup
{
public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; }
public void Configuration(IAppBuilder app)
{
OAuthOptions = new OAuthAuthorizationServerOptions()
{
TokenEndpointPath = new PathString("/token"),
Provider = new OAuthAuthorizationServerProvider()
{
OnValidateClientAuthentication = async (context) =>
{
context.Validated();
},
OnGrantResourceOwnerCredentials = async (context) =>
{
if (context.UserName == "test.test@mail.com" && context.Password == "test123")
{
ClaimsIdentity oAuthIdentity = new ClaimsIdentity(context.Options.AuthenticationType);
context.Validated(oAuthIdentity);
}
}
},
AllowInsecureHttp = true,
AccessTokenExpireTimeSpan = TimeSpan.FromDays(1)
};
app.UseOAuthBearerTokens(OAuthOptions);
}
}
}
프로젝트를 실행하십시오. 팝업에 토큰이 표시되어야합니다.
I am researching the same thing and stumbled upon identityserver which implements OAuth and OpenID on top of ASP.NET. It integrates with ASP.NET identity and Membership Reboot with persistence support for Entity Framework.
So, to answer your question, check out their detailed document on how to setup an OAuth and OpenID server.
Gmail: OAuth
- Goto the link
- Login with your gmail username password
- Click on the google menu at the top left
- Click API Manager
- Click on Credentials
- Click Create Credentials and select OAuth Client
- Select Web Application as Application type and Enter the Name-> Enter Authorised Redirect URL (Eg: http://localhost:53922/signin-google) ->Click on Create button. This will create the credentials. Pls make a note of
Client ID
andSecret ID
. Finally click OK to close the credentials pop up. - Next important step is to enable the
Google API
. Click on Overview in the left pane. - Click on the
Google API
under Social APIs section. - Click Enable.
That’s all from the Google part.
Come back to your application, open App_start/Startup.Auth.cs
and uncomment the following snippet
app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
{
ClientId = "",
ClientSecret = ""
});
Update the ClientId
and ClientSecret
with the values from Google API
credentials which you have created already.
- Run your application
- Click Login
- You will see the Google button under ‘Use Another Section to log in’ section
- Click on the Google button
- Application will prompt you to enter the username and password
- Enter the gmail username and password and click Sign In
- This will perform the OAuth and come back to your application and prompting you to register with the
Gmail
id. - Click register to register the
Gmail
id into your application database. - You will see the Identity details appear in the top as normal registration
- Try logout and login again thru Gmail. This will automatically logs you into the app.
'Programming' 카테고리의 다른 글
다른 스레드가 완료되었는지 확인하는 방법은 무엇입니까? (0) | 2020.07.12 |
---|---|
공유 객체에서 모든 심볼을 내보내는 방법은 무엇입니까? (0) | 2020.07.12 |
현재 파일의 전체 경로를 확장하여 Vim의 명령에 전달하려면 어떻게해야합니까? (0) | 2020.07.12 |
미디어 쿼리-두 너비 사이 (0) | 2020.07.12 |
JSON 배열을 통한 JavaScript 루프? (0) | 2020.07.12 |