【问题标题】:HttpContext.Current.GetOwinContext().Authentication.Challenge() Does not open adfs pageHttpContext.Current.GetOwinContext().Authentication.Challenge() 不打开 adfs 页面
【发布时间】:2019-09-27 02:18:57
【问题描述】:

我有一个与 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;

    }

【问题讨论】:

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


    【解决方案1】:

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

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

    OWIN 在附加到HttpContext 对象的IAuthenticationManager 接口中有自己的身份验证管理器版本。该对象处理用于通过站点跟踪用户的安全cookie 的创建和删除。身份 cookie 用于跟踪所有登录用户,无论他们是使用用户名和密码在本地登录还是使用 Google 等外部提供商登录。一旦用户通过身份验证,就会调用 SignIn 方法来创建 cookie。在随后的请求中,基于 OWIN 的身份子系统随后会获取 Cookie,并在用户访问您的网站时向用户授权相应的基于 IPrinciple(具有 ClaimsIdentity 的 ClaimsPrincipal)的用户。

    【讨论】:

    • 我的控制器继承自 UmbracoApiController,它是一个 ApiController,这意味着我无法像在控制器继承类中那样获取 HttpContext。我能做什么?
    • 查看此链接 - dotronald.be/…
    • 该链接没有解决他正在扩展 ApiController
    猜你喜欢
    • 2021-06-05
    • 1970-01-01
    • 1970-01-01
    • 2011-08-30
    • 2018-12-05
    • 2011-08-27
    • 2014-08-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多