Spring Security OAuth
Casdoor може використовувати протокол OIDC як IDP для підключення різних додатків. У цьому посібнику ми використаємо Spring Security як приклад, щоб показати вам, як використовувати OIDC для підключення до ваших додатків.
Крок 1: Розгортання Casdoor
Deploy Casdoor. See Server installation. Ensure the server is running and you can open the login page and sign in (e.g. admin / 123).
Крок 2. Налаштування додатку Casdoor
- Створіть новий додаток Casdoor або використайте існуючий.
- Додайте свій URL перенаправлення (Детальніше про отримання URL перенаправлення ви можете знайти в наступному розділі).

- Додайте бажаного провайдера та заповніть будь-які додаткові налаштування.
Note Client ID and Client secret from the application page for the next step. OIDC discovery: http://<CASDOOR_HOSTNAME>/.well-known/openid-configuration.
Крок 3. Налаштування Spring Security
Spring Security нативно підтримує OIDC.
Ви можете налаштувати параметри клієнта Spring Security OAuth2:
Replace the placeholders with your own Casdoor instance (Client ID, Client secret, etc.).
- application.yml
- application.properties
spring:
security:
oauth2:
client:
registration:
casdoor:
client-id: <Client ID>
client-secret: <Client Secret>
scope: <Scope>
authorization-grant-type: authorization_code
redirect-uri: <Redirect URL>
provider:
casdoor:
authorization-uri: http://CASDOOR_HOSTNAME:7001/login/oauth/authorize
token-uri: http://CASDOOR_HOSTNAME:8000/api/login/oauth/access_token
user-info-uri: http://CASDOOR_HOSTNAME:8000/api/get-account
user-name-attribute: name
spring.security.oauth2.client.registration.casdoor.client-id=<Client ID>
spring.security.oauth2.client.registration.casdoor.client-secret=<Client Secret>
spring.security.oauth2.client.registration.casdoor.scope=<Scope>
spring.security.oauth2.client.registration.casdoor.authorization-grant-type=authorization_code
spring.security.oauth2.client.registration.casdoor.redirect-uri=<Redirect URL>
spring.security.oauth2.client.provider.casdoor.authorization-uri=http://CASDOOR_HOSTNAME:7001/login/oauth/authorize
spring.security.oauth2.client.provider.casdoor.token-uri=http://CASDOOR_HOSTNAME:8000/api/login/oauth/access_token
spring.security.oauth2.client.provider.casdoor.user-info-uri=http://CASDOOR_HOSTNAME:8000/api/get-account
spring.security.oauth2.client.provider.casdoor.user-name-attribute=name
Для стандартної ситуації Spring Security, <Redirect URL> має бути подібним до http://<Your Spring Boot Application Endpoint>/<Servlet Prefix if it is configured>/login/oauth2/code/custom. Наприклад, у наступному демо-прикладі URL перенаправлення має бути http://localhost:8080/login/oauth2/code/custom.
Ви також повинні налаштувати це в додатку casdoor.
Ви також можете налаштувати параметри використовуючи ClientRegistration у вашому коді. Ви можете знайти відповідність тут
Крок 4: Почніть з демо
-
Ми можемо створити додаток Spring Boot.
-
Ми можемо додати конфігурацію, яка захищає всі кінцеві точки, крім
/та/login**, для входу користувачів.@EnableWebSecurity
public class UiSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/", "/login**")
.permitAll()
.anyRequest()
.authenticated()
.and()
.oauth2Login();
}
} -
Ми можемо додати просту сторінку для входу користувача.
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Spring OAuth Client Thymeleaf - 1</title>
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" />
</head>
<body>
<nav
class="navbar navbar-expand-lg navbar-light bg-light shadow-sm p-3 mb-5">
<a class="navbar-brand" th:href="@{/foos/}">Spring OAuth Client
Thymeleaf - 1</a>
</nav>
<div class="container">
<label>Welcome!</label> <br /> <a th:href="@{/foos/}"
class="btn btn-primary">Login</a>
</div>
</body>
</html>Коли користувач натискає кнопку
login, він буде перенаправлений наcasdoor. -
Далі ми можемо визначити наші захищені ресурси. Ми можемо відкрити кінцеву точку під назвою
/foosта веб-сторінку для відображення.Модель даних
public class FooModel {
private Long id;
private String name;
public FooModel(Long id, String name) {
super();
this.id = id;
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}Контролер
@Controller
public class FooClientController {
@GetMapping("/foos")
public String getFoos(Model model) {
List<FooModel> foos = new ArrayList<>();
foos.add(new FooModel(1L, "a"));
foos.add(new FooModel(2L, "b"));
foos.add(new FooModel(3L, "c"));
model.addAttribute("foos", foos);
return "foos";
}
}Веб-сторінка
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Spring OAuth Client Thymeleaf - 1</title>
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" />
</head>
<body>
<nav
class="navbar navbar-expand-lg navbar-light bg-light shadow-sm p-3 mb-5">
<a class="navbar-brand" th:href="@{/foos/}">Spring OAuth Client
Thymeleaf -1</a>
<ul class="navbar-nav ml-auto">
<li class="navbar-text">Hi, <span sec:authentication="name">preferred_username</span> </li>
</ul>
</nav>
<div class="container">
<h1>All Foos:</h1>
<table class="table table-bordered table-striped">
<thead>
<tr>
<td>ID</td>
<td>Name</td>
</tr>
</thead>
<tbody>
<tr th:if="${foos.empty}">
<td colspan="4">No foos</td>
</tr>
<tr th:each="foo : ${foos}">
<td>
<span th:text="${foo.id}">ID</span>
</td>
<td>
<span th:text="${foo.name}">Name</span>
</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
Усі шаблони веб-сторінок мають бути розміщені у resources/templates.
Крок 5: Спробуйте демо!
Open /foos in a browser; you are redirected to Casdoor’s login page. Sign in there or from the root page.
Якщо ви відвідаєте свою кореневу сторінку, ви побачите Налаштування додатку Casdoor.
Натисніть кнопку login і сторінка перенаправить вас на сторінку входу Casdoor. 
Після входу сторінка перенаправить вас на /foos. 