Spring Cloud Gateway
Das casdoor-springcloud-gateway-example ist ein Beispiel dafür, wie man den casdoor-spring-boot-starter als OAuth2-Plugin in Spring Cloud Gateway verwendet. Die Schritte zur Verwendung sind unten beschrieben.
Schritt 1: Casdoor einrichten
Deploy Casdoor in production mode. See Server installation. Ensure the server is reachable and you can sign in at the login page (e.g. admin / 123).
Schritt 2: Ein Spring Cloud Gateway initialisieren
Use the example code as-is or adapt it to your application.
Sie benötigen einen Gateway-Service und mindestens einen Geschäftsservice. In diesem Beispiel ist casdoor-gateway der Gateway-Service und casdoor-api der Geschäftsservice.
Schritt 3: Die Abhängigkeit einbinden
Fügen Sie die Abhängigkeit casdoor-spring-boot-starter zu Ihrem Spring Cloud Gateway-Projekt hinzu.
Für Apache Maven:
<!-- https://mvnrepository.com/artifact/org.casbin/casdoor-spring-boot-starter -->
<dependency>
<groupId>org.casbin</groupId>
<artifactId>casdoor-spring-boot-starter</artifactId>
<version>1.x.y</version>
</dependency>
Für Gradle:
// https://mvnrepository.com/artifact/org.casbin/casdoor-spring-boot-starter
implementation group: 'org.casbin', name: 'casdoor-spring-boot-starter', version: '1.x.y'
Schritt 4: Konfigurieren Sie Ihre Eigenschaften
Die Initialisierung erfordert 6 Parameter, die alle vom Typ String sind.
| Name (in Reihenfolge) | Erforderlich | Beschreibung |
|---|---|---|
| endpoint | Ja | Casdoor Server-URL, wie zum Beispiel http://localhost:8000 |
| clientId | Ja | Application.client_id |
| clientSecret | Ja | Application.client_secret |
| certificate | Ja | Application.certificate |
| organizationName | Ja | Application.organization |
| applicationName | Nein | Application.name |
Initialize these parameters via Java properties or YAML.
Für Eigenschaften:
casdoor.endpoint=http://localhost:8000
casdoor.clientId=<client-id>
casdoor.clientSecret=<client-secret>
casdoor.certificate=<certificate>
casdoor.organizationName=built-in
casdoor.applicationName=app-built-in
Für YAML:
casdoor:
endpoint: http://localhost:8000
client-id: <client-id>
client-secret: <client-secret>
certificate: <certificate>
organization-name: built-in
application-name: app-built-in
Configure gateway routing as well. Für YAML:
spring:
application:
name: casdoor-gateway
cloud:
gateway:
routes:
- id: api-route
uri: http://localhost:9091
predicates:
- Path=/api/**
Schritt 5: Den CasdoorAuthFilter hinzufügen
Fügen Sie eine Implementierungsklasse des GlobalFilter-Interfaces zum Gateway für die Identitätsüberprüfung hinzu, wie zum Beispiel den CasdoorAuthFilter, der in diesem Beispiel verwendet wird.
Wenn die Authentifizierung fehlschlägt, wird ein 401-Statuscode an das Frontend zurückgegeben, um sie zur Login-Schnittstelle umzuleiten.
@Component
public class CasdoorAuthFilter implements GlobalFilter, Ordered {
private static final Logger LOGGER = LoggerFactory.getLogger(CasdoorAuthFilter.class);
@Override public int getOrder() {
return 0;
}
@Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
return exchange.getSession().flatMap(webSession -> {
CasdoorUser user = webSession.getAttribute("casdoorUser");
if (user != null) {
return chain.filter(exchange);
}
ServerHttpResponse response = exchange.getResponse();
response.setStatusCode(HttpStatus.UNAUTHORIZED);
response.getHeaders().add("Content-Type", "application/json");
return response.setComplete();
});
}
}
Schritt 6: Den Service abrufen und verwenden
Jetzt bieten 5 Dienste an: CasdoorAuthService, CasdoorUserService, CasdoorEmailService, CasdoorSmsService und CasdoorResourceService.
Create them in the Gateway project as follows.
@Resource
private CasdoorAuthService casdoorAuthService;
When the app requires authentication, redirect to Casdoor's login page with the target URL.
Add the callback URL (e.g. http://localhost:9090/callback) to the Casdoor application in advance.
@RequestMapping("login")
public Mono<String> login() {
return Mono.just("redirect:" + casdoorAuthService.getSigninUrl("http://localhost:9090/callback"));
}
After Casdoor verifies the user, the app is redirected back with a code and state; use the code and getOAuthToken to obtain the JWT.
CasdoorUser holds the user info from Casdoor; use it to establish the session in your app.
@RequestMapping("callback")
public Mono<String> callback(String code, String state, ServerWebExchange exchange) {
String token = "";
CasdoorUser user = null;
try {
token = casdoorAuthService.getOAuthToken(code, state);
user = casdoorAuthService.parseJwtToken(token);
} catch(CasdoorAuthException e) {
e.printStackTrace();
}
CasdoorUser finalUser = user;
return exchange.getSession().flatMap(session -> {
session.getAttributes().put("casdoorUser", finalUser);
return Mono.just("redirect:/");
});
}
Beispiele für die APIs werden unten gezeigt.
- CasdoorAuthService
String token = casdoorAuthService.getOAuthToken(code, "app-built-in");CasdoorUser casdoorUser = casdoorAuthService.parseJwtToken(token);
- CasdoorUserService
CasdoorUser casdoorUser = casdoorUserService.getUser("admin");CasdoorUser casdoorUser = casdoorUserService.getUserByEmail("admin@example.com");CasdoorUser[] casdoorUsers = casdoorUserService.getUsers();CasdoorUser[] casdoorUsers = casdoorUserService.getSortedUsers("created_time", 5);int count = casdoorUserService.getUserCount("0");CasdoorResponse response = casdoorUserService.addUser(user);CasdoorResponse response = casdoorUserService.updateUser(user);CasdoorResponse response = casdoorUserService.deleteUser(user);
- CasdoorEmailService
CasdoorResponse response = casdoorEmailService.sendEmail(title, content, sender, receiver);
- CasdoorSmsService
CasdoorResponse response = casdoorSmsService.sendSms(randomCode(), receiver);
- CasdoorResourceService
CasdoorResponse response = casdoorResourceService.uploadResource(user, tag, parent, fullFilePath, file);CasdoorResponse response = casdoorResourceService.deleteResource(file.getName());
Schritt 7: Das Projekt neu starten
After starting the project, open your favorite browser and visit http://localhost:9090. Klicken Sie dann auf eine beliebige Schaltfläche, die Ressourcen von casdoor-api anfordert.

The gateway triggers auth; unauthenticated users are redirected to the login page. Click Login.

The Casdoor login page is shown.

After login, you are redirected to the main interface; you can proceed to use the app.

Was noch
For more on Java integration, see the following projects and docs.