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

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。

CRUD应用

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

CRUD应用

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保护应用程序的安全。 下面是该应用完成时的屏幕截图。

CRUD应用

您将需要安装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。

CRUD应用

创建一个目录来保存您的服务器和客户端应用程序。 我叫我的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 。 它具有有关其各种组件以及如何使用它们的大量文档。 右上角的油漆桶将允许您预览可用的主题颜色。

CRUD应用

使用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启动客户端应用程序。 您现在还看不到汽车清单,如果您打开开发者控制台,您将明白原因。

CRUD应用

发生此错误的原因是您尚未在服务器上启用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 ,则会看到汽车列表,但没有与之关联的图像。

CRUD应用

使用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);}});}
}

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

CRUD应用

向您的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>

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

CRUD应用

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

CRUD应用

将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 ,然后单击完成

CRUD应用

您将在页面底部看到客户端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时看到错误。

CRUD应用

注意:您可以通过将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

CRUD应用

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

CRUD应用

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

CRUD应用

了解有关Spring Boot和Angular的更多信息

跟上快速移动的框架(如Spring Boot和Angular)可能很难。 这篇文章旨在让您快速了解最新版本。 有关Angular 8的特定更改,请参阅Angular团队有关Angular 8版本的博客文章 。 对于Spring Boot,请参阅其2.2发行说明 。

您可以在oktadeveloper / okta-spring-boot-2-angular-8-example上的GitHub上看到本教程中开发的应用程序的完整源代码。

这个博客有大量的Spring Boot和Angular教程。 这是我的一些最爱:

  • 使用Angular和Electron构建桌面应用程序
  • 将您的Spring Boot应用程序迁移到最新和最新的Spring Security和OAuth 2.0
  • Java 11,Spring Boot和JavaScript中的i18n
  • 为Angular应用程序建立安全登录
  • 使用Spring WebFlux构建React性API

如有任何疑问,请随时在下面发表评论,或在我们的Okta开发者论坛上向我们提问。 别忘了在Twitter和YouTube 上关注我们!

变更日志:

  • 2019年6月4日:更新为使用Angular CLI 8.0.1,Angular 8.0.1和Angular Material 8.0.0。 您可以在okta-spring-boot-2-angular-8-example#3中看到示例应用程序的更改; 可以在okta.github.io#2911中查看对此职位的更改。

“ Angular 8 + Spring Boot 2.2:今天就构建一个CRUD应用程序!” 最初于2019年5月13日发布在Okta开发人员博客上。

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

翻译自: https://www.javacodegeeks.com/2019/06/angular-spring-boot-build-crud-app-today-2.html

angular1.2.27

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/332211.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

ssm中怎么用location.href跳到controller层_聊聊自动驾驶中的功能开发

在知乎上看过不少大牛写的自动驾驶技术介绍文章&#xff0c;大多谈到的是AI, Deep Learning, Computer Vision等等感知(Perception)层面的。但在各个传感器(雷达、摄像头、激光雷达等)探测到目标信息及周围环境后&#xff0c;车辆该如何做出反应&#xff1f;自动驾驶的大脑该怎…

MyEclipse详细使用教程

第一部分MyEclipse的基本使用 一&#xff0e;提示&#xff1a;MyEclipse的透视图按钮&#xff1a;可以切换不同的透视图&#xff08;位于右上角&#xff09; 1.建立一个工程 ----File—new—project—选项含有Javaproject&#xff0c;webproject等等—输入工程名字如myproject&…

控制语句(if-else+循环+switch)汇编规则

【1】说说条件码 最常用的的条件码有&#xff1a; CF&#xff1a;进位标志 &#xff08;无符号溢出&#xff09;ZF&#xff1a;零标志SF&#xff1a;符号标志&#xff08;结果为负数&#xff09;OF&#xff1a;溢出标志 &#xff08;补码溢出&#xff0c; 有符号溢出&#xf…

zxing qr区域判断_如何在Java中使用Zxing和JFreeSVG创建QR Code SVG?

zxing qr区域判断在本文中&#xff0c;我们将研究如何使用Zxing QR代码生成库和JFreeSVG库在Java中创建QR Code SVG图像。 QR码生成 下面的代码使用Zxing库创建一个表示QR Code的java.awt.image.BufferedImage对象&#xff1a; public static BufferedImage getQRCode(String …

审批流_怎样让审批工作流和应用数据分离?

在企业行政管理中&#xff0c;审批是最常遇到的场景。传统管理中&#xff0c;人们会有纸张审批&#xff0c;而现在市场上已有大量的线上审批软件&#xff0c;他们帮助企业完成审批电子化&#xff0c;审批速度更快&#xff0c;信息也能留档。然而大部分审批软件都不够灵活&#…

java 反射api_反射是最重要的Java API

java 反射api前几天我在想-这是最重要的Java API。 哪种SE和EE API可以使大多数Java生态系统成为可能&#xff0c;而哪些API不能重新创建为第三方库。 正如您可能已经猜到标题一样&#xff0c;我认为它是Reflection API 。 是的&#xff0c;它不可避免地是每个项目的直接或间接…

前端校验表单项内容是否合规的JS脚本代码

用途&#xff1a;校验ip地址的格式 输入&#xff1a;strIP&#xff1a;ip地址 返回&#xff1a;如果通过验证返回true,否则返回false&#xff1b; */ function isIP(strIP) { if (isNull(strIP)) return false; var re/^(\d).(\d).(\d).(\d)$/g //匹配IP地址的正则表达式 if(r…

过程(栈帧结构是干货)

【0】写在前面 过程&#xff08;栈帧结构是干货&#xff09;&#xff1b;本文总结于csapp&#xff0c; 加上自己的理解&#xff1b;【1】栈帧结构 每个函数的每次调用&#xff0c;都有它自己独立的一个栈帧&#xff0c;这个栈帧中维持着所需要的各种信息。 过程调用&#xf…

山东小学信息技术课本 python 五年级_山东教育出版社小学信息技术五年级上册教案 全册.doc...

山东教育出版社小学信息技术五年级上册教案 全册电子备课教学案学年度 第一学期学科 信息技术年级 五年级姓名教师个人备课情况统计一览表 项目?精备课二次备课课堂检测课后反思交流平台 篇数月份第( )月第( )月第( )月第( )月备注&#xff1a;为便于自查&#xff0c;此表由教…

apache ranger_Apache Ranger插件的美丽简洁

apache ranger如果您在这里&#xff0c;您已经知道什么是Apache Ranger 。 这是在Hadoop框架中管理安全性的最流行&#xff08;即使不是唯一&#xff09;的方法。 它与Active Directory&#xff0c;Kerberos和其他各种身份验证集成在一起&#xff0c;但是我认为最有趣的功能是其…

可重定位目标文件

【0】GCC将源代码转化成可执行代码的流程 &#xff08;1&#xff09;C预处理器cpp扩展源代码&#xff0c;插入所有用#include命令指定的文件&#xff0c;并扩展声明的宏&#xff1b;&#xff08;2&#xff09;编译器ccl产生两个源代码的汇编代码&#xff1a;*.s&#xff1b;&a…

经典颜色的RGB值

红 RED    品红Magenta&#xff08;热情&#xff09;    CMYK&#xff1a;C15 M100 Y20 K0   RGB: R207 G0 B112    洋红Carmine&#xff08;大胆&#xff09;   CMYK: C100 M0 Y60 K10   RGB: R215 G0 B64    宝石红Ruby&#xff08;富贵&#xff09;   CMYK…

python中for x in range_python教程:对 [lambda x: x*i for i in range(4)] 理解

题目&#xff1a;lst [lambda x: x*i for i in range(4)]res [m(2) for m in lst]print res实际输出&#xff1a;[6, 6, 6, 6]想要输出 [0, 2, 4, 6] 应该怎么改&#xff1f;如下&#xff1a;lst [lambda x, ii: x*i for i in range(4)]res [m(2) for m in lst]print res这…

adf.test_在ADF 12.2.1.3中使用基于JSON的REST Web服务

adf.test以前&#xff0c;我曾发布过有关在ADF中使用基于ADF BC的REST Web服务的信息。 现在&#xff0c;本文讨论使用通用数据控件使用基于JSON的REST Web服务。 您还可以查看有关Web服务的先前文章&#xff0c;以获取更多信息。 在ADF 12.2.1中使用应用程序模块快速创建SOA…

JSON字符串封装成Bean对象/JSON串反序列化成实体类对象/JSON字符串转换成Java对象

文章目录使用阿里巴巴的 JSON使用 ObjectMapperJSON字段与实体类属性不一致首先&#xff0c;我们建立一个实体类&#xff0c;这里简单定义了 name、sex、age 三个属性&#xff0c;以及 get、set、tostring方法。public class Student {private String name;private String sex;…

端到端的地址翻译(虚拟地址是怎样取到相应高速缓存的数据的?)

【0】写在前面-为什么需要虚拟存储器? 0.1&#xff09;定义&#xff1a;虚拟存储器其实就是借用了磁盘地址空间&#xff0c;还记得当初我们安装CentOS&#xff0c;划分的swap 文件系统吗&#xff1f; 0.2&#xff09;VM简化了链接和加载、代码和数据共享&#xff0c;以及应用…

python gevent教程_Python的gevent框架的入门教程

Python通过yield提供了对协程的基本支持&#xff0c;但是不完全。而第三方的gevent为Python提供了比较完善的协程支持。gevent是第三方库&#xff0c;通过greenlet实现协程&#xff0c;其基本思想是&#xff1a;当一个greenlet遇到IO操作时&#xff0c;比如访问网络&#xff0c…

qa/qc_专业QA如何实施可靠的CI / CD管道?

qa/qc过时的传统软件开发方法并不能接管不断升级的市场趋势&#xff0c;并且这些方法缺乏解决方案&#xff0c;无法解决引入“ 持续集成&#xff08;CI&#xff09;和持续交付&#xff08;CD&#xff09; ”的快速软件发布需求的增长。 除了CI / CD之外&#xff0c;您还需要具有…

程序员分类

1.优秀的debug能力 10K程序员&#xff1a;实现功能就不错了 20K程序员&#xff1a;编程我最牛&#xff0c;debug&#xff1f;我不太会&#xff01; 30K程序员&#xff1a;编程有点慢&#xff0c;debug快速搞定&#xff0c;回家睡觉&#xff01; 40K程序员&#xff1a;基本不写…

三菱q系列plc连接电脑步骤_三菱Q系列PLC与三菱变频器的CC-link通讯技术(我的学习笔记)...

三菱变频器可以通过CC-LINK的接线进行控制&#xff08;但需要另购买选件FR-A7NC&#xff0c;这选件是与变频器配套的通讯适配器&#xff0c;插在三菱变频器的选件插槽中&#xff09;&#xff0c;从而可以减少接线提高效率减少错误&#xff0c;接CC-LINK只需4根线就可以完全控制…