HttpContext.Current.GetOwinContext()。Authentication.Challenge()无法打开adfs页面

时间:2019-05-09 09:18:19

标签: c# angularjs asp.net-mvc single-sign-on adfs

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

我的角度检查“ GetUserRoles”功能,然后转移到本地登录页面。

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

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;

    }

1 个答案:

答案 0 :(得分:0)

请从UserAccountApiController中的以下代码中删除当前内容

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

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

OWIN在IAuthenticationManager对象的HttpContext界面中拥有自己的身份验证管理器版本。此对象处理创建和删除用于跟踪用户的安全cookie。网站。身份cookie用于跟踪所有登录的用户,无论他们是使用用户名和密码在本地登录还是使用外部提供商(如Google)登录。验证用户身份后,将调用SignIn方法创建cookie。在随后的请求中,基于OWIN的Identity子系统随后会在用户访问您的网站时,拾取Cookie并向用户授权适当的基于IPrinciple(具有ClaimsIdentity的ClaimsPrinciple)的用户。