angular1.2.27

“我喜欢编写身份验证和授权代码。” 〜从来没有Java开发人员。 厌倦了一次又一次地建立相同的登录屏幕? 尝试使用Okta API进行托管身份验证,授权和多因素身份验证。

如果您已经成为Java开发人员超过15年,那么您可能还记得何时有太多的Java Web框架。 它始于Struts和WebWork。 然后Tapestry,Wicket和JSF出现并倡导基于组件的框架的想法。 Spring MVC于2004年发布(与Flex 1.0和JSF 1.0同月发布),并在接下来的六年中成为Java Web框架的实际标准。

随之而来的是AngularJS,每个人都开始将其UI架构迁移到JavaScript。 Angular 2是在2014年首次发布Spring Boot的同时宣布的,它花了几年时间才发布,固化并成为可行的选择。 这些天,我们将其称为Angular,没有版本号。 最近的几个版本相当稳定,主要版本之间的升级路径很流畅。

今天,我想向您展示如何使用Angular和Spring Boot的最新和最佳版本构建应用程序。 Angular 8和Spring Boot 2.2都进行了性能改进,以改善开发人员的生活。

Angular 8有什么新功能?

Angular 8添加了差异加载,一个可选的Ivy Renderer和Bazel作为构建选项。 差异加载是CLI在构建已部署应用程序的一部分时构建两个单独的捆绑软件的地方。 现代捆绑软件可用于常绿的浏览器,而传统捆绑软件则包含所有旧浏览器所需的polyfill。


Ivy Renderer更小,更快,更易于调试,改进了类型检查,并且最重要的是向后兼容。


Spring Boot 2.2中有什么新功能?

Spring Boot在快速启动的框架(如Micronaut和Quarkus)中感到有些不适,并且也实现了许多性能改进。 现在默认情况下禁用JMX,禁用Hibernate的实体扫描,并且默认情况下启用Bean的惰性初始化。 另外,通过在Spring Boot的@Configuration类中使用proxyBeanMethods=false减少了启动时间和内存使用量。 有关更多信息,请参见Spring Boot 2.2 Release Notes 。

如果您使用这些框架的较旧版本,则可能需要查看我以前的几篇文章:

  • 使用Angular 7.0和Spring Boot 2.1构建基本的CRUD应用
  • 使用Angular 5.0和Spring Boot 2.0构建基本的CRUD应用

这篇文章介绍了如何构建一个简单的CRUD应用程序,该应用程序显示了一系列凉爽的汽车。 它允许您编辑汽车,并显示与汽车名称匹配的GIPHY动画gif。 您还将学习如何使用Okta的Spring Boot启动程序和Angular SDK保护应用程序的安全。 下面是该应用完成时的屏幕截图。


您将需要安装Java 11和Node.js 10+才能完成本教程。

使用Spring Boot 2.2构建API

要开始使用Spring Boot 2.2,请转到start.spring.io并创建一个使用Java 11(在更多选项下),Spring Boot版本2.2.0 M2和依赖项的新项目,以创建安全的API:JPA, H2,Rest Repository,Lombok,Okta和Web。


创建一个目录来保存您的服务器和客户端应用程序。 我叫我的okta-spring-boot-2-angular-8-example ,但是您可以随便叫什么。

如果您希望应用程序正在运行而不是编写代码,则可以在GitHub上查看示例 ,或使用以下命令在本地克隆并运行。

git clone https://github.com/oktadeveloper/okta-spring-boot-2-angular-8-example.git
cd okta-spring-boot-2-angular-8-example/client
npm install
ng serve &
cd ../server
./mvnw spring-boot:run

从start.spring.io下载demo.zip之后,展开它,然后将demo目录复制到您的应用程序持有人目录中。 将demo重命名为server 。 打开server/pom.xml并注释掉Okta的Spring Boot启动器上的依赖项。

<!--dependency><groupId>com.okta.spring</groupId><artifactId>okta-spring-boot-starter</artifactId><version>1.1.0</version>
</dependency-->

在您最喜欢的IDE中打开项目,并在src/main/java/com/okta/developer/demo目录中创建Car.java类。 您可以使用Lombok的注释来减少样板代码。

package com.okta.developer.demo;import lombok.*;import javax.persistence.Id;
import javax.persistence.GeneratedValue;
import javax.persistence.Entity;@Entity
@Data
@NoArgsConstructor
public class Car {@Id @GeneratedValueprivate Long id;private @NonNull String name;
}

创建一个CarRepository类以对Car实体执行CRUD(创建,读取,更新和删除)。

package com.okta.developer.demo;import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;@RepositoryRestResource
interface CarRepository extends JpaRepository<car, long=""> {
}
</car,>

ApplicationRunner bean添加到DemoApplication类(在src/main/java/com/okta/developer/demo/DemoApplication.java ),并使用它向数据库添加一些默认数据。

package com.okta.developer.demo;import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import java.util.stream.Stream;@SpringBootApplication
public class DemoApplication {public static void main(String[] args) {SpringApplication.run(DemoApplication.class, args);}@BeanApplicationRunner init(CarRepository repository) {return args -> {Stream.of("Ferrari", "Jaguar", "Porsche", "Lamborghini", "Bugatti","AMC Gremlin", "Triumph Stag", "Ford Pinto", "Yugo GV").forEach(name -> {Car car = new Car();car.setName(name);repository.save(car);});repository.findAll().forEach(System.out::println);};}
}

如果在添加此代码后启动应用程序(使用./mvnw spring-boot:run ),则会在启动时看到控制台中显示的汽车列表。

Car(id=1, name=Ferrari)
Car(id=2, name=Jaguar)
Car(id=3, name=Porsche)
Car(id=4, name=Lamborghini)
Car(id=5, name=Bugatti)
Car(id=6, name=AMC Gremlin)
Car(id=7, name=Triumph Stag)
Car(id=8, name=Ford Pinto)
Car(id=9, name=Yugo GV)

注意:如果看到Fatal error compiling: invalid target release: 11 ,这是因为您使用的是Java8。如果更改为使用Java 11,则该错误将消失。 如果您使用的是SDKMAN , 请先运行sdk install java 11.0.2-open然后运行sdk default java 11.0.2-open

添加一个CoolCarController类(在src/main/java/com/okta/developer/demo ),该类返回要在Angular客户端中显示的酷车列表。

package com.okta.developer.demo;import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Collection;
import java.util.stream.Collectors;@RestController
class CoolCarController {private CarRepository repository;public CoolCarController(CarRepository repository) {this.repository = repository;}@GetMapping("/cool-cars")public Collection<Car> coolCars() {return repository.findAll().stream().filter(this::isCool).collect(Collectors.toList());}private boolean isCool(Car car) {return !car.getName().equals("AMC Gremlin") &&!car.getName().equals("Triumph Stag") &&!car.getName().equals("Ford Pinto") &&!car.getName().equals("Yugo GV");}
}

如果重新启动服务器,并使用浏览器或命令行客户端访问http://localhost:8080/cool-cars ,则应该看到已过滤的汽车列表。

$ http :8080/cool-cars
HTTP/1.1 200
Content-Type: application/json;charset=UTF-8
Date: Tue, 07 May 2019 18:07:33 GMT
Transfer-Encoding: chunked[{"id": 1,"name": "Ferrari"},{"id": 2,"name": "Jaguar"},{"id": 3,"name": "Porsche"},{"id": 4,"name": "Lamborghini"},{"id": 5,"name": "Bugatti"}
]

使用Angular CLI创建客户端

Angular CLI是一个命令行实用程序,可以为您生成Angular项目。 它不仅可以创建新项目,而且还可以生成代码。 这是一个方便的工具,因为它还提供了一些命令,这些命令将生成和优化您的项目以进行生产。 它使用webpack在后台进行构建。

安装最新版本的Angular CLI(在撰写本文时为8.0.1版)。

npm i -g @angular/cli@8.0.1

在创建的伞形目录中创建一个新项目。

ng new client --routing --style css --enable-ivy

创建客户端后,导航至其目录,删除.git ,然后安装Angular Material。

cd client
rm -rf .git # optional: .git won't be created if you don't have Git installed
ng add @angular/material

当提示您提供主题和其他选项时,请选择默认值。

您将使用Angular Material的组件使UI看起来更好,尤其是在手机上。 如果您想了解有关Angular Material的更多信息,请参见material.angular.io 。 它具有有关其各种组件以及如何使用它们的大量文档。 右上角的油漆桶将允许您预览可用的主题颜色。


使用Angular CLI构建汽车列表页面

使用Angular CLI生成可以与Cool Cars API对话的汽车服务。

ng g s shared/car/car

更新client/src/app/shared/car/car.service.ts以从服务器获取汽车列表。

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';@Injectable({providedIn: 'root'
})
export class CarService {constructor(private http: HttpClient) {}getAll(): Observable<any> {return this.http.get('//localhost:8080/cool-cars');}
}

打开src/app/app.module.ts ,并将HttpClientModule添加为导入。

import { HttpClientModule } from '@angular/common/http';@NgModule({declarations: [AppComponent],imports: [BrowserModule,AppRoutingModule,BrowserAnimationsModule,HttpClientModule],providers: [],bootstrap: [AppComponent]
})

生成car-list组件以显示汽车列表。

ng g c car-list

更新client/src/app/car-list/car-list.component.ts以使用CarService来获取列表并在本地cars变量中设置值。

import { Component, OnInit } from '@angular/core';
import { CarService } from '../shared/car/car.service';@Component({selector: 'app-car-list',templateUrl: './car-list.component.html',styleUrls: ['./car-list.component.css']
})
export class CarListComponent implements OnInit {cars: Array<any>;constructor(private carService: CarService) { }ngOnInit() {this.carService.getAll().subscribe(data => {this.cars = data;});}
}

更新client/src/app/car-list/car-list.component.html以显示汽车列表。

<h2>Car List</h2><div *ngFor="let car of cars">{{car.name}}
</div>

更新client/src/app/app.component.html以具有app-car-list元素。

<div style="text-align:center"><h1>Welcome to {{ title }}!</h1>
</div><app-car-list></app-car-list>
<router-outlet></router-outlet>

使用ng serve -o启动客户端应用程序。 您现在还看不到汽车清单,如果您打开开发者控制台,您将明白原因。


发生此错误的原因是您尚未在服务器上启用CORS(跨源资源共享)。

在服务器上启用CORS

要在服务器上启用CORS,添加@CrossOrigin注释到CoolCarController (在server/src/main/java/com/okta/developer/demo/CoolCarController.java )。

import org.springframework.web.bind.annotation.CrossOrigin;
...
@GetMapping("/cool-cars")
@CrossOrigin(origins = "http://localhost:4200")
public Collection<Car> coolCars() {return repository.findAll().stream().filter(this::isCool).collect(Collectors.toList());
}

在Spring启动版本2.1.4及以下,你还可以添加一个@CrossOrigin注释您CarRepository 。 从Angular添加/删除/编辑时,这将允许您与其端点进行通信。

import org.springframework.web.bind.annotation.CrossOrigin;@RepositoryRestResource
@CrossOrigin(origins = "http://localhost:4200")
interface CarRepository extends JpaRepository<Car, Long> {
}

但是,这在Spring Boot 2.2.0.M2中不再起作用 。 好消息是有解决方法。 您可以将CorsFilter bean添加到DemoApplication.java类中。 当您还集成Spring Security时,这是必需的。 您只是要早一点做。

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.core.Ordered;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import java.util.Collections;...public class DemoApplication {// main() and init() methods@Beanpublic FilterRegistrationBean<CorsFilter> simpleCorsFilter() {UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();CorsConfiguration config = new CorsConfiguration();config.setAllowCredentials(true);config.setAllowedOrigins(Collections.singletonList("http://localhost:4200"));config.setAllowedMethods(Collections.singletonList("*"));config.setAllowedHeaders(Collections.singletonList("*"));source.registerCorsConfiguration("/**", config);FilterRegistrationBean<CorsFilter> bean = new FilterRegistrationBean<>(new CorsFilter(source));bean.setOrder(Ordered.HIGHEST_PRECEDENCE);return bean;}
}

重新启动服务器,刷新客户端,您应该在浏览器中看到汽车列表。

添加角材料

您已经安装了Angular Material,要使用其组件,需要导入它们。 打开client/src/app/app.module.ts并添加动画的导入,以及Material的工具栏,按钮,输入,列表和卡片布局。

import { MatButtonModule, MatCardModule, MatInputModule, MatListModule, MatToolbarModule } from '@angular/material';@NgModule({...imports: [BrowserModule,AppRoutingModule,BrowserAnimationsModule,HttpClientModule,MatButtonModule,MatCardModule,MatInputModule,MatListModule,MatToolbarModule],...
})

更新client/src/app/app.component.html以使用工具栏组件。

<mat-toolbar color="primary"><span>Welcome to {{title}}!</span>
</mat-toolbar><app-car-list></app-car-list>
<router-outlet></router-outlet>

更新client/src/app/car-list/car-list.component.html以使用卡片布局和列表组件。

<mat-card><mat-card-title>Car List</mat-card-title><mat-card-content><mat-list><mat-list-item *ngFor="let car of cars"><img mat-list-avatar src="{{car.giphyUrl}}" alt="{{car.name}}"><h3 mat-line>{{car.name}}</h3></mat-list-item></mat-list></mat-card-content>
</mat-card>

如果使用ng serve运行客户端并导航到http://localhost:4200 ,则会看到汽车列表,但没有与之关联的图像。


使用Giphy添加动画GIF

要将giphyUrl属性添加到每辆汽车,请创建client/src/app/shared/giphy/giphy.service.ts并使用以下代码填充。

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { map } from 'rxjs/operators';@Injectable({providedIn: 'root'})
export class GiphyService {// This is a Giphy API Key I created. Create your own at https://developers.giphy.com/dashboard/?create=true.giphyApi = '//api.giphy.com/v1/gifs/search?api_key=nOTRbUNMgD5mj4XowN2ERoPNudAkK6ft&limit=1&q=';constructor(public http: HttpClient) {}get(searchTerm) {const apiLink = this.giphyApi + searchTerm;return this.http.get(apiLink).pipe(map((response: any) => {if (response.data.length > 0) {return response.data[0].images.original.url;} else {return 'https://media.giphy.com/media/YaOxRsmrv9IeA/giphy.gif'; // dancing cat for 404}}));}
}

更新client/src/app/car-list/car-list.component.ts以在每辆汽车上设置giphyUrl属性。

import { Component, OnInit } from '@angular/core';
import { CarService } from '../shared/car/car.service';
import { GiphyService } from '../shared/giphy/giphy.service';@Component({selector: 'app-car-list',templateUrl: './car-list.component.html',styleUrls: ['./car-list.component.css']
})
export class CarListComponent implements OnInit {cars: Array<any>;constructor(private carService: CarService, private giphyService: GiphyService) { }ngOnInit() {this.carService.getAll().subscribe(data => {this.cars = data;for (const car of this.cars) {this.giphyService.get(car.name).subscribe(url => car.giphyUrl = url);}});}
}

现在,您的浏览器将显示汽车名称列表以及它们旁边的头像图像。


向您的Angular应用添加编辑功能

列出汽车名称和图像很酷,但是当您可以与其互动时,它会更加有趣! 要添加编辑功能,请首先生成car-edit组件。

ng g c car-edit

更新client/src/app/shared/car/car.service.ts以具有添加,移除和更新汽车的方法。 这些方法跟由提供的端点CarRepository及其@RepositoryRestResource注释。

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';@Injectable({providedIn: 'root'})
export class CarService {public API = '//localhost:8080';public CAR_API = this.API + '/cars';constructor(private http: HttpClient) {}getAll(): Observable<any> {return this.http.get(this.API + '/cool-cars');}get(id: string) {return this.http.get(this.CAR_API + '/' + id);}save(car: any): Observable<any> {let result: Observable<any>;if (car.href) {result = this.http.put(car.href, car);} else {result = this.http.post(this.CAR_API, car);}return result;}remove(href: string) {return this.http.delete(href);}
}

client/src/app/car-list/car-list.component.html ,添加指向编辑组件的链接。 另外,在底部添加按钮以添加新车。

<mat-card><mat-card-title>Car List</mat-card-title><mat-card-content><mat-list><mat-list-item *ngFor="let car of cars"><img mat-list-avatar src="{{car.giphyUrl}}" alt="{{car.name}}"><h3 mat-line><a mat-button [routerLink]="['/car-edit', car.id]">{{car.name}}</a></h3></mat-list-item></mat-list></mat-card-content><button mat-fab color="primary" [routerLink]="['/car-add']">Add</button>
</mat-card>

client/src/app/app.module.ts ,导入FormsModule

import { FormsModule } from '@angular/forms';@NgModule({...imports: [...FormsModule],...
})

client/src/app/app-routing.module.ts ,为CarListComponentCarEditComponent添加路由。

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { CarListComponent } from './car-list/car-list.component';
import { CarEditComponent } from './car-edit/car-edit.component';const routes: Routes = [{ path: '', redirectTo: '/car-list', pathMatch: 'full' },{path: 'car-list',component: CarListComponent},{path: 'car-add',component: CarEditComponent},{path: 'car-edit/:id',component: CarEditComponent}
];@NgModule({imports: [RouterModule.forRoot(routes)],exports: [RouterModule]
})
export class AppRoutingModule { }

修改client/src/app/car-edit/car-edit.component.ts以从URL上传递的ID中获取汽车的信息,并添加保存和删除方法。

import { Component, OnDestroy, OnInit } from '@angular/core';
import { Subscription } from 'rxjs';
import { ActivatedRoute, Router } from '@angular/router';
import { CarService } from '../shared/car/car.service';
import { GiphyService } from '../shared/giphy/giphy.service';
import { NgForm } from '@angular/forms';@Component({selector: 'app-car-edit',templateUrl: './car-edit.component.html',styleUrls: ['./car-edit.component.css']
})
export class CarEditComponent implements OnInit, OnDestroy {car: any = {};sub: Subscription;constructor(private route: ActivatedRoute,private router: Router,private carService: CarService,private giphyService: GiphyService) {}ngOnInit() {this.sub = this.route.params.subscribe(params => {const id = params.id;if (id) {this.carService.get(id).subscribe((car: any) => {if (car) {this.car = car;this.car.href = car._links.self.href;this.giphyService.get(car.name).subscribe(url => car.giphyUrl = url);} else {console.log(`Car with id '${id}' not found, returning to list`);this.gotoList();}});}});}ngOnDestroy() {this.sub.unsubscribe();}gotoList() {this.router.navigate(['/car-list']);}save(form: NgForm) {this.carService.save(form).subscribe(result => {this.gotoList();}, error => console.error(error));}remove(href) {this.carService.remove(href).subscribe(result => {this.gotoList();}, error => console.error(error));}
}

更新client/src/app/car-edit/car-edit.component.htmlHTML,以具有带有汽车名称的表单,并显示来自Giphy的图像。

<mat-card><form #carForm="ngForm" (ngSubmit)="save(carForm.value)"><mat-card-header><mat-card-title><h2>{{car.name ? 'Edit' : 'Add'}} Car</h2></mat-card-title></mat-card-header><mat-card-content><input type="hidden" name="href" [(ngModel)]="car.href"><mat-form-field><input matInput placeholder="Car Name" [(ngModel)]="car.name"required name="name" #name></mat-form-field></mat-card-content><mat-card-actions><button mat-raised-button color="primary" type="submit"[disabled]="!carForm.valid">Save</button><button mat-raised-button color="secondary" (click)="remove(car.href)"*ngIf="car.href" type="button">Delete</button><a mat-button routerLink="/car-list">Cancel</a></mat-card-actions><mat-card-footer><div class="giphy"><img src="{{car.giphyUrl}}" alt="{{car.name}}"></div></mat-card-footer></form>
</mat-card>

通过将以下CSS添加到client/src/app/car-edit/car-edit.component.css ,在图像周围添加一些填充。

.giphy {margin: 10px;
}

修改client/src/app/app.component.html并删除<app-car-list></app-car-list>

<mat-toolbar color="primary"><span>Welcome to {{title}}!</span>
</mat-toolbar><router-outlet></router-outlet>

进行所有这些更改之后,您应该可以添加,编辑或删除任何汽车。 下面的屏幕快照显示了带有添加按钮的列表。


以下屏幕截图显示了编辑已添加的汽车的外观。


将OIDC身份验证添加到您的Spring Boot + Angular App中

使用OIDC添加身份验证是一个不错的功能,可以添加到此应用程序中。 如果您想添加审核或个性化您的应用程序(例如,使用评分功能),那么知道此人的身份将非常有用。

Spring安全+ OIDC

在服务器端,您可以使用Okta的Spring Boot Starter来锁定一切,它利用了Spring Security及其OIDC支持。 打开server/pom.xml并取消注释Okta Spring Boot启动器。

<dependency><groupId>com.okta.spring</groupId><artifactId>okta-spring-boot-starter</artifactId><version>1.1.0</version>
</dependency>

现在,您需要配置服务器以使用Okta进行身份验证。 为此,您需要在Okta中创建OIDC应用。

在Okta中创建OIDC应用

登录到您的1563开发者帐户(或者注册 ,如果你没有一个帐户)并导航到应用程序 > 添加应用程序 。 单击“ 单页应用程序” ,再单击“ 下一步” ,然后为应用程序命名。 将所有http://localhost:8080实例更改为http://localhost:4200 ,然后单击完成


您将在页面底部看到客户端ID。 将它和issuer属性添加到server/src/main/resources/application.properties

okta.oauth2.client-id={yourClientId}
okta.oauth2.issuer=https://{yourOktaDomain}/oauth2/default

创建server/src/main/java/com/okta/developer/demo/SecurityConfiguration.java以将您的Spring Boot应用配置为资源服务器。

package com.okta.developer.demo;import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().anyRequest().authenticated().and().oauth2ResourceServer().jwt();}
}

进行这些更改之后,您应该能够重新启动应用程序,并在尝试导航到http://localhost:8080时看到错误。


注意:您可以通过将http://localhost:8080/login/oauth2/code/okta为应用程序的重定向URI来解决此错误,但这不能解决问题。 如果您想通过Spring Boot支持OIDC登录,则需要注册一个Web应用程序(而不是SPA),并在application.properties包含一个客户端密码。 这不是本教程中的必要步骤。

现在您的服务器已被锁定,您需要配置客户端以使用访问令牌与之对话。 这就是Okta的Angular SDK派上用场的地方。

Okta的角度支撑

Okta Angular SDK是Okta Auth JS的包装,后者基于OIDC。 可以在GitHub上找到有关Okta的Angular库的更多信息。

为了简化Angular SDK的安装和配置,我们创建了一个@ oktadev / schematics项目,该项目可以为您完成所有工作。 您可以在“ 使用角度示意图简化生活”中阅读有关@ oktadev / schematics如何工作的更多信息。

在安装它之前,最好将您的项目检查到源代码管理中。 如果未安装Git,则可以将项目复制到另一个位置作为备份。 如果确实安装了Git,请从项目的根目录中运行以下命令。

git init
git add .
git commit -m "Initialize project"

要安装和配置Okta的Angular SDK,请在client目录中运行以下命令:

ng add @oktadev/schematics --issuer=https://{yourOktaDomain}/oauth2/default --clientId={yourClientId}

该命令将:

  • 安装@okta/okta-angular
  • auth-routing.module.ts为您的应用配置Okta的Angular SDK
  • isAuthenticated逻辑添加到app.component.ts
  • 添加带有登录和注销按钮的HomeComponent
  • 使用到/home的默认路由和/implicit/callback路由配置路由
  • 添加一个HttpInterceptor ,该HttpInterceptorlocalhost请求添加带有访问令牌的Authorization标头

auth-routing.module.ts文件添加到默认路由HomeComponent ,所以你需要删除默认的app-routing.module.ts 。 修改app-routing.module.ts以删除第一个路由并添加OktaAuthGuard 。 这样可以确保在访问路由之前对用户进行身份验证。

import { OktaAuthGuard } from '@okta/okta-angular';const routes: Routes = [{path: 'car-list',component: CarListComponent,canActivate: [OktaAuthGuard]},{path: 'car-add',component: CarEditComponent,canActivate: [OktaAuthGuard]},{path: 'car-edit/:id',component: CarEditComponent,canActivate: [OktaAuthGuard]}
];

修改client/src/app/app.component.html以使用Material组件并具有一个注销按钮。

<mat-toolbar color="primary"><span>Welcome to {{title}}!</span><span class="toolbar-spacer"></span><button mat-raised-button color="accent" *ngIf="isAuthenticated"(click)="oktaAuth.logout()" [routerLink]="['/home']">Logout</button>
</mat-toolbar><router-outlet></router-outlet>

您可能会注意到toolbar-spacer类存在跨度。 要使此功能按预期工作,请在client/src/app/app.component.css添加一个toolbar-spacer规则。

.toolbar-spacer {flex: 1 1 auto;
}

然后更新client/src/app/home/home.component.html以使用Angular Material并链接到Car List。

<mat-card><mat-card-content><button mat-raised-button color="accent" *ngIf="!isAuthenticated"(click)="oktaAuth.loginRedirect()">Login</button><button mat-raised-button color="accent" *ngIf="isAuthenticated"[routerLink]="['/car-list']">Car List</button></mat-card-content>
</mat-card>

由于您使用的是HomeComponent Material组件,该组件由新添加的client/src/app/auth-routing.module.ts ,因此需要导入MatButtonModuleMatCardModule

import { MatButtonModule, MatCardModule } from '@angular/material';@NgModule({...imports: [...MatButtonModule,MatCardModule],...
})

要使其内容底部没有底边框,请通过将以下内容添加到client/src/styles.css来使<mat-card>元素填充屏幕。

mat-card {height: 100vh;
}

现在,如果您重新启动客户端,一切都应该工作。 不幸的是,这不是因为Ivy尚未实现CommonJS / UMD支持 。 解决方法是,您可以修改tsconfig.app.json以禁用Ivy。

"angularCompilerOptions": {"enableIvy": false
}

停止并重新启动ng serve过程。 打开浏览器到http://localhost:4200


单击登录按钮。 如果一切配置正确,您将被重定向到Okta登录。


输入有效的凭据,您应该被重定向回您的应用程序。 庆祝一切成功!

angular1.2.27_Angular 8 + Spring Boot 2.2:立即构建一个CRUD应用程序!相关推荐

  1. IDEA 2019 生成Spring Boot项目,编写第一个Hello World程序,并打包成jar

    IDEA集成了生成Spring Boot项目的功能,不需要你去 start.spring.io 上下载,使用方法如下: 新建项目,选择Spring Initializr: 然后点NEXT: 勾选需要的 ...

  2. Angular 8 + Spring Boot 2.2:立即构建一个CRUD应用程序!

    "我喜欢编写身份验证和授权代码." 〜从来没有Java开发人员. 厌倦了一次又一次地建立相同的登录屏幕? 尝试使用Okta API进行托管身份验证,授权和多因素身份验证. 如果您已 ...

  3. Spring Boot中使用Swagger2构建RESTful APIs

    关于 Swagger Swagger能成为最受欢迎的REST APIs文档生成工具之一,有以下几个原因: Swagger 可以生成一个具有互动性的API控制台,开发者可以用来快速学习和尝试API. S ...

  4. Spring Boot 参考指南(运行你的应用程序)

    19. 运行你的应用程序 将你的应用程序打包为jar并使用嵌入式HTTP服务器的最大优点之一是,你可以像对待其他应用程序一样运行应用程序,调试Spring Boot应用程序也很简单,你不需要任何特殊的 ...

  5. Spring Boot 中使用 Swagger2 构建强大的 RESTful API 文档

    项目现状:由于前后端分离,没有很好的前后端合作工具. 由于接口众多,并且细节复杂(需要考虑不同的HTTP请求类型.HTTP头部信息.HTTP请求内容等),高质量地创建这份文档本身就是件非常吃力的事,下 ...

  6. java Spring Boot中使用Swagger2构建API文档

    1.添加Swagger2的依赖 在pom.xml中加入Swagger2的依赖 <dependency><groupId>io.springfox</groupId> ...

  7. Spring Boot(二)——项目热部署与程序发布

    一.项目热部署 1.1 配置依赖 ① pom.xml加入devtools依赖,如果scope是provided则无法实现热部署,参考. <dependency><groupId> ...

  8. Spring Boot中使用Swagger2构建强大的RESTful API文档

    由于Spring Boot能够快速开发.便捷部署等特性,相信有很大一部分Spring Boot的用户会用来构建RESTful API.而我们构建RESTful API的目的通常都是由于多终端的原因,这 ...

  9. Spring boot 使用QQ邮箱进行一个验证登入

    Spring boot 使用QQ邮箱进行一个验证登入 QQ邮箱开启权限 在QQ邮箱设置->账户里面,往下拉找到这个开启,手机号验证成功后会有一串英文字符串是待会儿要用到的密码. prom.xml ...

最新文章

  1. 未来哲学的六个问题域
  2. 旋转目标检测rotation-yolov5笔记
  3. 030_CSS外边距合并
  4. JDBC告警系列(一)The server time zone value 'ÖÐ' is unrecognized or represents more than one time zone....
  5. arachni web mysql数据库_Web安全扫描工具Arachni
  6. python dry原则_关于Python 的这几个技巧,你应该知道
  7. python设置一个初始为0的计数器_python中统计计数的几种方法
  8. [TED] Kinect控制的四翼直升机
  9. shell交互式输入
  10. 网络***检查分析---破解安全隐患问题回答
  11. 【转】支持向量机回归模型SVR
  12. R语言绘图(一)热图
  13. 安装在ntfs分区的linux,从硬盘NTFS分区安装mandriva linux
  14. java面向对象编程(六)--四大特征之继承
  15. DTM使用途中的bug记录
  16. h5开发安卓机型点击输入框调起输入法,输入框被键盘遮挡的解决方法
  17. cut命令的详细用法
  18. 电脑wifi可以登录qq,但是不可以上网,怎么办?
  19. 03709马原第三章考点总结
  20. 如何进行简单的区块链编程,也许LISK是个选项

热门文章

  1. 吉吉王国(二分+树形dp)
  2. 【AcWing 243. 一个简单的整数问题2】
  3. # CF1572B Xor of 3(构造)
  4. CF1322C:Instant Noodles
  5. YBTOJ洛谷P3750:分手是祝愿(期望dp)
  6. jzoj6805-NOIP2020.9.26模拟speike【扫描线】
  7. 欢乐纪中A组周六赛【2019.3.30】
  8. jzoj3519-灵能矩阵【LCM,树形dp】
  9. 【线段树】Serious Business(CF1648D)
  10. Codefroces1077F2. Pictures with Kittens (hard version)