HttpContext.Current.GetOwinContext().Authentication.Challenge() 不打开 adfs 页面

Was*_*san 5 c# asp.net-mvc adfs single-sign-on angularjs

我有一个与 Angular JS 一起使用的单页 MVC 应用程序。Angular 从我的 asp mvc 应用程序调用 api,包括登录。我想向我的应用程序添加单点登录

在转移到本地登录页面之前,我的角度检查“GetUserRoles”功能..

我做错了什么,所以 UserAccountApiController 中的 HttpContext.Current.GetOwinContext().Authentication.Challenge() 行无法打开 adfs sso 页面???

用户帐户Api控制器

    [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;

    }
Run Code Online (Sandbox Code Playgroud)

启动.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);
    }
}
Run Code Online (Sandbox Code Playgroud)

网页配置

<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/" />
Run Code Online (Sandbox Code Playgroud)

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) { }
}
Run Code Online (Sandbox Code Playgroud)

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;

    }
Run Code Online (Sandbox Code Playgroud)

小智 5

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

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

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

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

  • 我的控制器继承自 UmbracoApiController,它是一个 ApiController,这意味着我无法像在 Controller 继承类中那样获取 HttpContext。我能做些什么 ? (2认同)
  • 该链接没有解决他正在扩展 ApiController (2认同)