oauth 토큰을 사용하여 웹 API 2 기반 클레임 기반 인증을 구현하려고합니다. 이를 위해 제가 웹 API 2에서 OWIN 베어러 인증에 실패했습니다.
[assembly: OwinStartup(typeof(PMW.Api.Startup))]
public class Startup
{
//private IUnitOfWork _unitOfWork;
//private IUserService _userService;
//private ICommonService _commonService;
public void Configuration(IAppBuilder app)
{
HttpConfiguration config = new HttpConfiguration();
WebApiConfig.Register(config);
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
app.UseWebApi(config);
IUnityContainer container = GetUnityContainer();
config.DependencyResolver = new UnityDependancyResolver(container);
//_unitOfWork = container.Resolve<IUnitOfWork>();
//_userService = container.Resolve<IUserService>();
//_commonService = container.Resolve<ICommonService>();
MapAutomapper();
ConfigureOAuth(app);
//var OAuthBearerOptions = new OAuthBearerAuthenticationOptions()
//{
// Provider = new QueryStringOAuthBearerProvider(),
// AccessTokenProvider = new AuthenticationTokenProvider()
// {
// OnCreate = create,
// OnReceive = receive
// },
//};
//app.UseOAuthBearerAuthentication(OAuthBearerOptions);
}
public static Action<AuthenticationTokenCreateContext> create = new Action<AuthenticationTokenCreateContext>(c =>
{
c.SetToken(c.SerializeTicket());
});
public static Action<AuthenticationTokenReceiveContext> receive = new Action<AuthenticationTokenReceiveContext>(c =>
{
c.DeserializeTicket(c.Token);
c.OwinContext.Environment["Properties"] = c.Ticket.Properties;
});
private void MapAutomapper()
{
//Mapper code
}
private IUnityContainer GetUnityContainer()
{
//Create UnityContainer
IUnityContainer container = //unity mapping
return container;
}
public void ConfigureOAuth(IAppBuilder app)
{
OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
Provider = new SimpleAuthorizationServerProvider()
};
// Token Generation
app.UseOAuthAuthorizationServer(OAuthServerOptions);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
}
}
생성하고 권한 클래스 코드가 올바르게 작동하고 클라이언트 측 애플리케이션에 대한 토큰을 생성
public class SimpleAuthorizationServerProvider : OAuthAuthorizationServerProvider
{
public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
context.Validated();
}
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
IUnityContainer container = //unity code for mapping login related service
var _commonService=container.Resolve<ICommonService>() ;
var password =// Encrypt password
UserService _userService = new UserService(container.Resolve<IUnitOfWork>(),
container.Resolve<IUserMasterRepository>(), container.Resolve<IUserDetailRepository>());
var userToPass = new UserDTO()
{
EmailId = context.UserName,
Password = password
};
var user = _userService.AuthenticateUser(userToPass);
if (!user.Succeeded)
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
return;
}
var identity = new ClaimsIdentity(context.Options.AuthenticationType);
identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
identity.AddClaim(new Claim(ClaimTypes.Role, "user"));
context.Validated(identity);
}
}
다음과 같이 정의된다. 그러나 아래와 같이 Authrize 속성을 사용하면됩니다. 오류 401이 권한이없는 상태로 항상 실패합니다.
[Authorize]
[HttpGet]
public UserDTO Test()
{
return new UserDTO();
}
다음은 요청 및 실패한 메소드 세부 정보의 스냅 샷입니다.
권한 흐름을 올바르게 구현하려면 누락 된 부분을 알려주십시오.
테스트 방법에서 GET을 수행하는 방법을 보여줄 수 있습니까? 내 말은, 보내는 중입니다. 승인 : 무기명을 요청 헤더로 올바르게 입력 했습니까? –
권한 보유자 토큰과 함께 요청 부분에 대한 참조를 포함하는 스냅 샷을 추가했습니다. – parth1729
스냅 샷의 정보에서 권한 부여와 자원을위한 두 개의 프로젝트가있는 것으로 보입니다. 두 webconfig 파일의 machinekey가 동일한 지 확인 했습니까? 이 질문을 확인하십시오 : http://stackoverflow.com/questions/25901414/owin-authentication-between-mvc-5-and-web-api-separate-iis-applications/25942811#25942811 –