首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Owin持有者令牌认证+授权控制器

Owin持有者令牌认证+授权控制器
EN

Stack Overflow用户
提问于 2014-08-01 10:08:34
回答 4查看 32.1K关注 0票数 20

我正在尝试使用持有者令牌和owin进行身份验证。

我可以使用授权类型password并覆盖AuthorizationServerProvider.cs.中的GrantResourceOwnerCredentials来发出令牌

但是我不能使用带有Authorize属性的控制器方法。

下面是我的代码:

Startup.cs

代码语言:javascript
复制
public class Startup
{
    public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; }

    // normal
    public Startup() : this(false) { }

    // testing
    public Startup(bool isDev)
    {
        // add settings
        Settings.Configure(isDev);

        OAuthOptions = new OAuthAuthorizationServerOptions
        {
            AllowInsecureHttp = true,
            TokenEndpointPath = new PathString("/Token"),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
            Provider = new AuthorizationServerProvider()
        };
    }

    public void Configuration(IAppBuilder app)
    {
        // Configure the db context, user manager and role manager to use a single instance per request
        app.CreatePerOwinContext(ApplicationDbContext.Create);
        app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
        app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);
        app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);
        app.CreatePerOwinContext<LoanManager>(BaseManager.Create);

        var config = new HttpConfiguration();
        WebApiConfig.Register(config);
        app.UseWebApi(config);

        // token generation
        app.UseOAuthAuthorizationServer(OAuthOptions);
        app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions
        {
            AuthenticationType = "Bearer",
            AuthenticationMode = AuthenticationMode.Active
        });
    }
}

AuthorizationServerProvider.cs

代码语言:javascript
复制
public class AuthorizationServerProvider : OAuthAuthorizationServerProvider
{
    public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
    {
        context.Validated();
    }

    public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
        context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
        var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();

        IdentityUser user = await userManager.FindAsync(context.UserName, context.Password);

        if (user == null)
        {
            context.SetError("invalid_grant", "The user name or password is incorrect.");
            return;
        }

        var identity = new ClaimsIdentity(context.Options.AuthenticationType);
        identity.AddClaim(new Claim("sub", context.UserName));
        identity.AddClaim(new Claim("role", "user"));

        context.Validated(identity);
    }
}

WebApiConfig.cs

代码语言:javascript
复制
public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.MapHttpAttributeRoutes();

        // enable CORS for all hosts, headers and methods
        var cors = new EnableCorsAttribute("*", "*", "*");
        config.EnableCors(cors);

        config.Routes.MapHttpRoute(
            name: "optional params",
            routeTemplate: "api/{controller}"
        );

        config.Routes.MapHttpRoute(
            name: "Default",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

        // stop cookie auth
        config.SuppressDefaultHostAuthentication();
        // add token bearer auth
        config.Filters.Add(new MyAuthenticationFilter());
        //config.Filters.Add(new HostAuthenticationFilter(Startup.OAuthOptions.AuthenticationType));

        config.Filters.Add(new ValidateModelAttribute());

        if (Settings.IsDev == false)
        {
            config.Filters.Add(new AuthorizeAttribute());
        }

        // make properties on model camelCased
        var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
        jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

        config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
    }

用于调试的MyAuthenticationFilter.cs自定义筛选器

代码语言:javascript
复制
public class MyAuthenticationFilter : ActionFilterAttribute, IAuthenticationFilter
{
    public Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
    {
        if (context.Principal != null && context.Principal.Identity.IsAuthenticated)
        {
        }

        return Task.FromResult(0);
    }

    public Task ChallengeAsync(HttpAuthenticationChallengeContext context, CancellationToken cancellationToken)
    {
        throw new System.NotImplementedException();
    }
}

如果我在MyAuthenticationFilter.cs中调试AuthenticateAsync,我会看到请求中的头:

代码语言:javascript
复制
Authorization: Bearer AQAAANCMnd8BFdERjHoAwE_Cl...

但是身份声明是空的,context.Principal.Identity.IsAuthenticated是假的。

有什么想法吗?

EN

回答 4

Stack Overflow用户

发布于 2014-10-26 22:11:04

我一直在寻找同样的解决方案,我花了一周左右的时间来解决这个问题,然后就离开了。今天我又开始搜索,我找到了你的问题,我希望能找到答案。

所以我花了一整天的时间尝试所有可能的解决方案,彼此合并建议,我找到了一些解决方案,但它们是很长的变通办法,长话短说,这是我发现的。

首先,如果您需要使用自定义的第三方身份提供者令牌对网站进行身份验证,则需要让它们使用相同的machineKey,或者将它们放在同一台服务器上。

您需要将machineKey添加到system.web部分,如下所示:

Web.Config

代码语言:javascript
复制
<system.web>
    <authentication mode="None" />
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5" />
    <machineKey validationKey="*****" decryptionKey="***" validation="SHA1" decryption="AES" />
</system.web>

以下是generate a new machineKey的链接:

现在,您需要移到可以在其中找到Startup.cs分部类的Startup.Auth.cs文件,还需要定义OAuthBearerOptions

Startup.Auth.cs

代码语言:javascript
复制
public partial class Startup
{
    public static OAuthBearerAuthenticationOptions OAuthBearerOptions { get; private set; }
    ...

    public void ConfigureAuth(IAppBuilder app)
    {
        // Configure the db context, user manager and signin manager to use a single instance per    request
        app.CreatePerOwinContext(ApplicationDbContext.Create);
        app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);

        OAuthBearerOptions = new OAuthBearerAuthenticationOptions();
        app.UseOAuthBearerAuthentication(OAuthBearerOptions);
        ...
    }
}

将AccountController中的登录操作替换为以下内容:

AccountController.cs

代码语言:javascript
复制
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
    /*This will depend totally on how you will get access to the identity provider and get your token, this is just a sample of how it would be done*/
    /*Get Access Token Start*/
    HttpClient httpClient = new HttpClient();
    httpClient.BaseAddress = new Uri("https://youridentityproviderbaseurl");
    var postData = new List<KeyValuePair<string, string>>();
    postData.Add(new KeyValuePair<string, string>("UserName", model.Email));
    postData.Add(new KeyValuePair<string, string>("Password", model.Password));
    HttpContent content = new FormUrlEncodedContent(postData);


    HttpResponseMessage response = await httpClient.PostAsync("yourloginapi", content);
    response.EnsureSuccessStatusCode();
    string AccessToken = Newtonsoft.Json.JsonConvert.DeserializeObject<string>(await response.Content.ReadAsStringAsync());
    /*Get Access Token End*/

    If(!string.IsNullOrEmpty(AccessToken))
    {
            var ticket = Startup.OAuthBearerOptions.AccessTokenFormat.Unprotect(AccessToken);
            var id = new ClaimsIdentity(ticket.Identity.Claims, DefaultAuthenticationTypes.ApplicationCookie);
            AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = true }, id);

            return RedirectToLocal(returnUrl);

   }

   ModelState.AddModelError("Error", "Invalid Authentication");
   return View();
}

您需要做的最后一件事是将这行代码放在Global.asax.cs中,以避免出现防伪造异常:

Global.asax.cs

代码语言:javascript
复制
public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier;

        …
    }
}

希望这对你有用。

票数 7
EN

Stack Overflow用户

发布于 2016-02-10 08:47:59

自从这篇文章发表一年以来,我也遇到了同样的问题。

如您所见,我的持有者令牌在请求标头中被识别,但我的身份仍未通过身份验证。

要解决这个问题,简短的答案是确保在配置OAuth中间件(HttpConfiguration)之前配置WebApi中间件。

票数 4
EN

Stack Overflow用户

发布于 2015-07-10 05:47:08

嗯,我已经在这上面工作了一段时间了,我终于找出了问题所在,现在它起作用了。

在GrantResourceOwnerCredentials方法上启用Cors的代码似乎以某种方式覆盖了来自参数的头。所以,把你的第一行放在当前的第三行下面,你的问题就解决了:

代码语言:javascript
复制
    var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();

    IdentityUser user = await userManager.FindAsync(context.UserName, context.Password);

   context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

到目前为止,我还没有更深入地了解为什么会这样,但我认为,在获取userManager之前添加新的头条目会以某种方式破坏客户端上post方法发送的数据,在我的例子中,是这样的角度资源:

代码语言:javascript
复制
    function userAccount($resource, appSettings) {
    return {
        registration: $resource(appSettings.serverPath + "/api/Account/Register", null, 
                {
                    'registerUser' : { method : 'POST'}
                }
            ),
        login : $resource(appSettings.serverPath + "/Token", null, 
                {
                    'loginUser': {
                        method: 'POST',
                        headers: {
                            'Content-Type' : 'application/x-www-form-urlencoded' 
                        },
                        transformRequest: function (data, headersGetter) {
                            var str = [];
                            for (var d in data) {
                                str.push(encodeURIComponent(d) + "=" + encodeURIComponent(data[d]));
                            }
                            return str.join("&"); 
                        }
                    }
                } 
            )
    }
}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25071817

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档