HttpContext.Current.GetOwinContext()。Authentication.Challenge()无法打开adfs页面 [英] HttpContext.Current.GetOwinContext().Authentication.Challenge() Does not open adfs page

查看:144
本文介绍了HttpContext.Current.GetOwinContext()。Authentication.Challenge()无法打开adfs页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个可与angular js一起使用的单页mvc应用程序。 Angular从我的ASP MVC应用程序(包括登录名)中调用api。我想在应用程序中添加单点登录



我的角度检查 GetUserRoles函数,然后转移到本地登录页面..



我在做错什么,因此UserAccountApiController中的HttpContext.Current.GetOwinContext()。Authentication.Challenge()行无法打开adfs sso页???



UserAccountApiController

  [HttpPost] 
public bool IsLogedInRoled(NR角色)
{
if(User.Identity.IsAuthenticated)
{
if(!string.IsNullOrEmpty(role.role))
{
var isLogedInRoled = GetUserRoles()。Select(x => x.ToLower())。包含(role.role);
返回isLogedInRoled;
}
返回true;
}
HttpContext.Current.GetOwinContext()。Authentication.Challenge(new AuthenticationProperties {RedirectUri =〜/},
WsFederationAuthenticationDefaults.AuthenticationType);

返回false;

}

Startup.cs

 公共类CustomeStartup:UmbracoDefaultOwinStartup 
{
私有静态字符串域= ConfigurationManager.AppSettings [ ida:Wtrealm ];
私有静态字符串adfsMetadata = ConfigurationManager.AppSettings [ ida:ADFSMetadata];
私有静态字符串adfsWreply = ConfigurationManager.AppSettings [ ida:Wreply];

公共替代无效配置(IAppBuilder应用)
{
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions {CookieName = E-services});
app.UseWsFederationAuthentication(new WsFederationAuthenticationOptions
{
Wtrealm = realm,
MetadataAddress = adfsMetadata,
Notifications = new WsFederationAuthenticationNotifications()
{
//此方法将在成功登录后调用,对于首次登录
SecurityTokenValidated = context =>
{
ClaimsIdentity identity = context.AuthenticationTicket.Identity;
//在此我们可以添加声明并指定类型,在我的情况下,我想添加角色声明
string [] role = {};
role = NParser.ToDecimal(identity.Name)> 0
?new [] {学生}
:new [] {雇员};
identity.AddClaim(new Claim(ClaimTypes.Role,role.First()));
// identi ty.AddClaim(new Claim(ClaimTypes.Role, somethingelse));
返回Task.FromResult(0);
},
RedirectToIdentityProvider = context =>
{
context.ProtocolMessage.Wreply = adfsWreply;
返回Task.FromResult(0);
}
},
});
app.UseStageMarker(PipelineStage.Authenticate);
base.Configuration(app);
}
}

Web.config

 <添加键= owin:appStartup value = CustomeStartup /> 
< add key = ida:ADFSMetadata value = https://udsts.ud.edu.sa/federationmetadata/2007-06/federationmetadata.xml />
< add key = ida:Wtrealm value = https://10.31.26.28/ />
<添加密钥= ida:Wreply value = https://10.31.26.28/ />

auth-guard.service.ts

 从 @ angular / core导入{可注入}; 
import {ActivatedRouteSnapshot,RouterStateSnapshot,Router}来自 @ angular / router;从 app / services / auth / auth.service中导入
{AuthService};

@ Injectable()
出口类AuthGuardService {
isloggedIn = false;
canActivate(route:ActivatedRouteSnapshot,state:RouterStateSnapshot){
const absorver =
this.auth
.checkLogedinRole(route.data)
.take(1);

absorver.toPromise()。then(x => {
this.isloggedIn = x;
if(!x){
this.router.navigate (['login']);
}
});
返还absorver;
}
构造函数(私有路由器:路由器,私有auth:AuthService){}
}

auth.service.ts

  public checkLogedinRole(角色:对象) :可观察的< any> {
const url =‘/ umbraco / api / UserAccountApi / IsLogedInRoled’;
返回this.http.post(URL,角色)
.map(x => x.json())
.catch(this._httpService.handleError);
}
公共登录名(模型:LoginModel):Observable< boolean> {
const status = false;

const headers = new Headers({‘Access-Control-Allow-Origin’:’*’});
const options = new RequestOptions({headers:headers});

const obs = this.http.post('/ umbraco / api / UserAccountApi / login',model,options)
.map(x => x.json())
.catch(this._httpService.handleError);

return obs;

}


解决方案

请删除当前来自UserAccountApiController中的以下代码

 旧-HttpContext.Current.GetOwinContext()。Authentication.Challenge(new AuthenticationProperties {RedirectUri = 〜/},
WsFederationAuthenticationDefaults.AuthenticationType);

新增-HttpContext.GetOwinContext()。Authentication.Challenge(new AuthenticationProperties {RedirectUri =〜/},
WsFederationAuthenticationDefaults.AuthenticationType);

OWIN在 IAuthenticationManager 接口,该接口附加到 HttpContext 对象。此对象处理创建和删除用于跟踪用户通过站点的安全cookie。身份cookie用于跟踪所有登录的用户,无论他们是使用用户名和密码在本地登录还是使用外部提供商(如Google)登录。验证用户身份后,将调用SignIn方法创建cookie。在随后的请求中,基于OWIN的Identity子系统随后将拾取Cookie并向用户授权相应的基于用户的 IPrinciple (具有ClaimsIdentity的ClaimsPrinciple)用户。 / p>

I have an single page mvc application that works with angular js. Angular calls api from my asp mvc application including the login. I want to add single sign on to my application

My angular check "GetUserRoles" function before transferring to the local login page ..

What I am doing wrong, so the line HttpContext.Current.GetOwinContext().Authentication.Challenge() in UserAccountApiController does not open adfs sso page ???

UserAccountApiController

    [HttpPost]
    public bool IsLogedInRoled(NR role)
    {
        if (User.Identity.IsAuthenticated)
        {
            if (!string.IsNullOrEmpty(role.role))
            {
                var isLogedInRoled = GetUserRoles().Select(x => x.ToLower()).Contains(role.role);
                return isLogedInRoled;
            }
            return true;
        }
        HttpContext.Current.GetOwinContext().Authentication.Challenge(new AuthenticationProperties { RedirectUri = "~/" },
            WsFederationAuthenticationDefaults.AuthenticationType);

        return false;

    }

Startup.cs

public class CustomeStartup : UmbracoDefaultOwinStartup
{
    private static string realm = ConfigurationManager.AppSettings["ida:Wtrealm"];
    private static string adfsMetadata = ConfigurationManager.AppSettings["ida:ADFSMetadata"];
    private static string adfsWreply = ConfigurationManager.AppSettings["ida:Wreply"];

    public override void Configuration(IAppBuilder app)
    {
        app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
        app.UseCookieAuthentication(new CookieAuthenticationOptions { CookieName = "E-services" });
        app.UseWsFederationAuthentication(new WsFederationAuthenticationOptions
        {
            Wtrealm = realm,
            MetadataAddress = adfsMetadata,
            Notifications = new WsFederationAuthenticationNotifications()
            {
                // this method will be invoked after login succes , for the first login
                SecurityTokenValidated = context =>
                {
                    ClaimsIdentity identity = context.AuthenticationTicket.Identity;
                    // here we can add claims and specify the type, in my case i want to add Role Claim
                    string[] roles = { };
                    roles = NParser.ToDecimal(identity.Name) > 0
                        ? new[] { "Student" }
                        : new[] { "Employee" };
                    identity.AddClaim(new Claim(ClaimTypes.Role, roles.First()));
                    //identity.AddClaim(new Claim(ClaimTypes.Role, "somethingelse"));
                    return Task.FromResult(0);
                },
                RedirectToIdentityProvider = context =>
                {
                    context.ProtocolMessage.Wreply = adfsWreply;
                    return Task.FromResult(0);
                }
            },
        });
        app.UseStageMarker(PipelineStage.Authenticate);
        base.Configuration(app);
    }
}

Web.config

<add key="owin:appStartup" value="CustomeStartup" />
<add key="ida:ADFSMetadata" value="https://udsts.ud.edu.sa/federationmetadata/2007-06/federationmetadata.xml" />
<add key="ida:Wtrealm" value="https://10.31.26.28/" />
<add key="ida:Wreply" value="https://10.31.26.28/" />

auth-guard.service.ts

import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
import { AuthService } from 'app/services/auth/auth.service';

@Injectable()
export class AuthGuardService {
    isloggedIn = false;
    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
        const absorver =
            this.auth
                .checkLogedinRole(route.data)
                .take(1);

        absorver.toPromise().then(x => {
            this.isloggedIn = x;
            if (!x) {
                this.router.navigate(['login']);
            }
        });
        return absorver;
    }
    constructor(private router: Router, private auth: AuthService) { }
}

auth.service.ts

    public checkLogedinRole(role: object): Observable<any> {
        const url = '/umbraco/api/UserAccountApi/IsLogedInRoled';
        return this.http.post(url, role)
            .map(x => x.json())
            .catch(this._httpService.handleError);
    }
    public login(model: LoginModel): Observable<boolean> {
        const status = false;

        const headers = new Headers({ 'Access-Control-Allow-Origin': '*' });
        const options = new RequestOptions({ headers: headers });

        const obs = this.http.post('/umbraco/api/UserAccountApi/login', model, options)
            .map(x => x.json())
            .catch(this._httpService.handleError);

        return obs;

    }

解决方案

Please remove current from below code in your UserAccountApiController

 Old - HttpContext.Current.GetOwinContext().Authentication.Challenge(new AuthenticationProperties { RedirectUri = "~/" },
           WsFederationAuthenticationDefaults.AuthenticationType);

New - HttpContext.GetOwinContext().Authentication.Challenge(new AuthenticationProperties { RedirectUri = "~/" },
           WsFederationAuthenticationDefaults.AuthenticationType);

OWIN has its own version of an authentication manager in the IAuthenticationManager interface which is attached to the HttpContext object.This object handles creation and deleting of the secure cookie that is used to track the user through the site. The identity cookie is used to track all logged in users, regardless of whether they logged in locally with a username and password or using an external provider like Google. Once a user is authenticated, the SignIn method is called to create the cookie. On subsequent requests, OWIN based Identity subsystem then picks up the Cookie and authorizes the user the appropriate IPrinciple (a ClaimsPrinciple with a ClaimsIdentity) based User whenever the user accesses your site.

这篇关于HttpContext.Current.GetOwinContext()。Authentication.Challenge()无法打开adfs页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆