返回首页 | 申博娱乐APP下载

合作共赢、快速高效、优质的网站建设提供商

更多精品源码-尽在织梦模板-www.moke8.com

网站开发运用angular4和asp.net core 2 web api做个操练项目(三)

时间:2017-11-03 编辑:admin

榜首部分:

第二部分:

后台代码:

前台代码:

下面将研制登陆和授权的部分, 这儿要用到identity server 4.

在VS解决方案中设置多个项目一起发动:

AspNetIdentityAuthorizationServer就是authorization server. 它的地址是 http://localhost:5000

CoreApi.Web作为api, 都现已装备好了.它的地址是 http://localhost:5001

Login 登陆

因为我们们运用的是Identity Server 4的登录页面, 所以angular项目里边无需登录页面, 把login相关的文件删去...........

登陆需求运用到oidc-client.php所以经过npm装置:

npm install --save oidc-client
Auth Service

需求登陆效劳 auth.service:

ng g s services/auth

翻开auth.services.ts:

import { Injectable, OnInit, EventEmitter } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { User, UserManager, Log } from 'oidc-client';
import 'rxjs/add/observable/fromPromise';
const config: any = {
 authority: 'http://localhost:5000',
 client_id: 'corejs',
 redirect_uri: 'http://localhost:4200/login-callback',
 response_type: 'id_token token',
 scope: 'openid profile coreapi',
 post_logout_redirect_uri: 'http://localhost:4200/index.html',
Log.logger = console;
Log.level = Log.DEBUG;
@Injectable()
export class AuthService implements OnInit {
 private manager: UserManager = new UserManager(config);
 public loginStatusChanged: EventEmitter User ;
 constructor() {
 this.loginStatusChanged = new EventEmitter();
 ngOnInit() {
 login() {
 this.manager.signinRedirect();
 loginCallBack() {
 return Observable.create(observer = {
 Observable.fromPromise(this.manager.signinRedirectCallback())
 .subscribe(() = {
 this.tryGetUser().subscribe((user: User) = {
 this.loginStatusChanged.emit(user);
 observer.next(user);
 observer.complete();
 }, e = {
 observer.error(e);
 checkUser() {
 this.tryGetUser().subscribe((user: User) = {
 this.loginStatusChanged.emit(user);
 }, e = {
 this.loginStatusChanged.emit(null);
 private tryGetUser() {
 return Observable.fromPromise(this.manager.getUser());
 logout() {
 this.manager.signoutRedirect();
}

config是针对identity server 4效劳器的装备, authorization server的地址是 http://localhost:5000, 登陆成功后跳转后来的地址是:http://localhost:4200/login-callback

其间的UserManager就是oidc-client里边的东西, 它负责处理登录登出和获取当时登录用户等操作.

这儿login()挑选被调用后会直接跳转到 authorization server的登录页面.

登录成功后会跳转到一个callback页面, 里边需求调用一个callback挑选, 这就是loginCallback()挑选.

loginStatusChanged是一个EventEmitter, 任何订阅了这个事情的component, 都会在登录用户改变时(登录/退出)触发component里边自定义的事情.

logout()是退出, 调用挑选后也会跳转到authorization server的页面.

最终别忘了在app.module里边注册:

 providers: [
 ClientService,
 AuthService
 ],

登陆成功后跳转回掉页面

树立一个跳转回掉的component和路由:

ng g c components/loginCallback

修正app.module的路由:

const appRoutes: Routes = [
 { path: '', component: DashboardComponent },
 { path: 'login-callback', component: LoginCallbackComponent },
 { path: 'register', component: RegisterComponent },
 { path: 'add-client', component: AddClientComponent },
 { path: 'client/:id', component: ClientDetailsComponent },
 { path: 'edit-client/:id', component: EditClientComponent }
];

翻开login-callback.component.ts:

import { Component, OnInit } from '@angular/core';
import { AuthService } from '../../services/auth.service';
import { Router } from '@angular/router';
import { User } from 'oidc-client';
@Component({
 selector: 'app-login-callback',
 templateUrl: './login-callback.component.html',
 styleUrls: ['./login-callback.component.cs*******port class LoginCallbackComponent implements OnInit {
 constructor(
 private authService: AuthService,
 private router: Router
 ) { }
 ngOnInit() {
 this.authService.loginCallBack().subscribe(
 (user: User) = {
 console.log('login callback user:', user);
 if (user) {
 this.router.navigate(['/']);
}

这儿主要是调用oidc的回掉函数. 然后跳转到主页.

html:

 p 
 登录成功!
 /p 

这个html, 基本是看不见的.

修正Navbar

navbar.component.html:

 nav 
 div 
 a href="#" Client Panel /a 
 button type="button" data-toggle="collapse" data-target="#navbarsExampleDefault" aria-controls="navbarsExampleDefault"
 aria-expanded="false" aria-label="Toggle navigation" 
 span /span 
 /button 
 div id="navbarsExampleDefault" 
 li *ngIf="isLoggedIn" 
 a href="#" routerLink="/" Dashboard /a 
 /li 
 /ul 
 li *ngIf="!isLoggedIn" 
 a href="#" routerLink="/register" Register /a 
 /li 
 li *ngIf="!isLoggedIn" 
 a href="#" (click)="login()" Login /a 
 /li 
 li *ngIf="isLoggedIn" 
 a href="#" (click)="logout()" Logout /a 
 /li 
 /ul 
 /div 
 /div 
 /nav 
 br 

主要是查看是否有用户登陆了, 有的话不显现注册和登陆链接, 而且显现退出链接按钮. 没有的话, 则显现注册和登录.

navbar.component.ts:

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { AuthService } from '../../services/auth.service';
import 'rxjs/add/operator/map';
import { User } from 'oidc-client';
import { FlashMessagesService } from 'angular2-flash-messages';
@Component({
 selector: 'app-navbar',
 templateUrl: './navbar.component.html',
 styleUrls: ['./navbar.component.cs*******port class NavbarComponent implements OnInit {
 public isLoggedIn: boolean;
 public loggedInUser: User;
 constructor(
 private authService: AuthService,
 private router: Router,
 private flashMessagesService: FlashMessagesService
 ) { }
 ngOnInit() {
 this.authService.loginStatusChanged.subscribe((user: User) = {
 this.loggedInUser = user;
 this.isLoggedIn = !!user;
 if (user) {
 this.flashMessagesService.show('登陆成功', { cssClass: 'alert alert-success', timeout: 4000 });
 this.authService.checkUser();
 login() {
 this.authService.login();
 logout() {
 this.authService.logout();
}

在ngOnInit里边订阅authservice的那个登录状况改变的事情. 以便切换导航栏的按钮显现状况.

angular的部分先到这, 然后要

修正一个identity server的装备:

在VS2017翻开AspNetIdentityAuthorizationServer这个项目的Config.cs文件, 看GetClients()那部分, 里边有一个Client是js client, 我们们就用这个....

// JavaScript Client
 new Client
 ClientId = CoreApiSettings.Client.ClientId,
 ClientName = CoreApiSettings.Client.ClientName,
 AllowedGrantTypes = GrantTypes.Implicit,
 AllowAccessTokensViaBrowser = true,
 RedirectUris = { CoreApiSettings.Client.RedirectUris },
 PostLogoutRedirectUris = { CoreApiSettings.Client.PostLogoutRedirectUris },
 AllowedCorsOrigins = { CoreApiSettings.Client.AllowedCorsOrigins },
 AllowedScopes =
 IdentityServerConstants.StandardScopes.OpenId,
 IdentityServerConstants.StandardScopes.Profile,
 CoreApiSettings.CoreApiResource.Name
 }

翻开CoreApiSettings, 它在SharedSettings这个项目里边:

namespace SharedSettings.Settings
 public class CoreApiSettings
 #region CoreApi
 public static string AuthorizationServerBase = "http://localhost:5000";
 public static string CorsPolicyName = "default";
 public static string CorsOrigin = "http://localhost:4200";
 public static (string Name, string DisplayName) CoreApiResource = ("coreapi", "Core APIs");
 public static (string ClientId, string ClientName, string RedirectUris, string PostLogoutRedirectUris, string AllowedCorsOrigins) Client =
 ("corejs", "Core Javascript Client", "http://localhost:4200/login-callback", "http://localhost:4200/index.html", "http://localhost:4200");
 #endregion
}

把相应的地址改成和angular auth.service里边config一样的地址才干作业.

这儿面运用了C# 7的命名Tuple, 十分好用.

差不多能够了, 运转VS. 一起运转angular项目:

1. 初次阅读:

2. 点击登陆:

点击登陆就跳转到authorization server的登录页面了, 你在这儿需求注册一个用户.....

然后输入用户名暗码登陆.

3.赞同授权

点击yes 赞同授权.

4.跳转回angular页面:

首要跳转回的是angular的login-callback路由, 然后瞬间回到了主页:

5. 改写, 仍是能够取得到登录的用户.

可是如果再翻开一个阅读器实例就无法取得到登陆用户了, oidc应该是把登陆信息存到了session storage里边.

翻开阅读器F12--Application:

能够看到在session storage里边的确有东西, 而 localstorage里边却没有.

今日比较忙, 先写到这... 估量还得写一篇....


浏览:

网站建设

流程

    网站建设流程