Spring Security filter (OIDC)
This guide integrates Casdoor with your application using Spring Security Filter and OIDC.
步骤1:部署Casdoor
Deploy the Casdoor server. After deployment, confirm:
- The Casdoor server is running at
http://localhost:8000. - The Casdoor login page is at
http://localhost:7001. - Test login with credentials
adminand123.
验证这些步骤后,按照下面的步骤将Casdoor与您的应用程序集成。
Step 2: Configure the Casdoor application
- Create or edit a Casdoor application and add your redirect URL (see next section for how to get it).

- 在证书编辑页面上获取你的
Certificate。
- 根据需要添加提供商和其他设置。
Note Application Name, Organization Name, Redirect URL, Client ID, Client Secret, and Certificate from the application page for the next step.
步骤3:配置Spring Security
Customize the Spring Security filter to process tokens:
Replace the placeholders with your own Casdoor instance (Client ID, Client secret, etc.).
server:
port: 8080
casdoor:
endpoint: http://CASDOOR_HOSTNAME:8000
client-id: <Client ID>
client-secret: <Client Secret>
certificate: <Certificate>
organization-name: <Organization Name>
application-name: <Application Name>
redirect-url: http://FRONTEND_HOSTNAME/callback
Default <FRONTEND_HOSTNAME> is localhost:3000; redirect URL is http://localhost:3000/callback. Add this redirect URL in the Casdoor application.
步骤4:配置前端
Install casdoor-js-sdk and configure it as follows:
-
安装
casdoor-js-sdk。npm i casdoor-js-sdk
# or
yarn add casdoor-js-sdk -
设置
SDK。import Sdk from "casdoor-js-sdk";
// Serverurl is the URL where spring security is deployed
export const ServerUrl = "http://BACKEND_HOSTNAME:8080";
const sdkConfig = {
serverUrl: "http://CASDOOR_HOSTNAME:8000",
clientId: "<your client id>",
appName: "<your application name>",
organizationName: "<your organization name>",
redirectPath: "/callback",
};
export const CasdoorSDK = new Sdk(sdkConfig);
步骤5:设置演示
-
创建一个Spring Boot应用程序。
-
添加一些配置来处理JWT。
@EnableWebSecurity
public class SecurityConfig {
private final JwtTokenFilter jwtTokenFilter;
public SecurityConfig(JwtTokenFilter jwtTokenFilter) {
this.jwtTokenFilter = jwtTokenFilter;
}
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
// 启用CORS并禁用CSRF
http = http.cors(corsConfig -> corsConfig
.configurationSource(configurationSource())
).csrf().disable();
// 将会话管理设置为无状态
http = http
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and();
// 在端点上设置权限
http.authorizeHttpRequests(authorize -> authorize
.mvcMatchers("/api/redirect-url", "/api/signin").permitAll()
.mvcMatchers("/api/**").authenticated()
);
// 设置未经授权的请求异常处理程序
http = http
.exceptionHandling()
.authenticationEntryPoint(
(request, response, ex) -> ResponseUtils.fail(response, "unauthorized")
)
.and();
// 添加JWT令牌过滤器
http.addFilterBefore(
jwtTokenFilter,
UsernamePasswordAuthenticationFilter.class
);
return http.build();
}
// ...
} -
添加一个简单的JWT过滤器来拦截需要令牌验证的请求。
@Component
public class JwtTokenFilter extends OncePerRequestFilter {
private final CasdoorAuthService casdoorAuthService;
public JwtTokenFilter(CasdoorAuthService casdoorAuthService) {
this.casdoorAuthService = casdoorAuthService;
}
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response,
FilterChain chain)
throws ServletException, IOException {
// 获取授权头并验证
final String header = request.getHeader(HttpHeaders.AUTHORIZATION);
if (!StringUtils.hasText(header) || !header.startsWith("Bearer ")) {
chain.doFilter(request, response);
return;
}
// 获取jwt令牌并验证
final String token = header.split(" ")[1].trim();
// 获取用户身份并将其设置在spring security上下文中
UserDetails userDetails = null;
try {
CasdoorUser casdoorUser = casdoorAuthService.parseJwtToken(token);
userDetails = new CustomUserDetails(casdoorUser);
} catch (CasdoorAuthException exception) {
logger.error("casdoor auth exception", exception);
chain.doFilter(request, response);
return;
}
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
userDetails,
null,
AuthorityUtils.createAuthorityList("ROLE_casdoor")
);
authentication.setDetails(
new WebAuthenticationDetailsSource().buildDetails(request)
);
SecurityContextHolder.getContext().setAuthentication(authentication);
chain.doFilter(request, response);
}
}当用户访问需要身份验证的接口时,
JwtTokenFilter将从请求头Authorization获取令牌并验证。 -
定义一个
Controller来处理用户登录Casdoor时的情况。 用户登录后,他们将被重定向到服务器并携带code和state。 然后服务器需要从Casdoor验证用户的身份,并通过这两个参数获取token。@RestController
public class UserController {
private static final Logger logger = LoggerFactory.getLogger(UserController.class);
private final CasdoorAuthService casdoorAuthService;
// ...
@PostMapping("/api/signin")
public Result signin(@RequestParam("code") String code, @RequestParam("state") String state) {
try {
String token = casdoorAuthService.getOAuthToken(code, state);
return Result.success(token);
} catch (CasdoorAuthException exception) {
logger.error("casdoor auth exception", exception);
return Result.failure(exception.getMessage());
}
}
// ...
}
步骤6:尝试演示
Open the frontend in a browser. When not logged in, a login button is shown; clicking it redirects to the Casdoor login page.
如果你访问你的根页面,
点击Casdoor Login按钮,页面将重定向到Casdoor的登录页面。 
After login, the app redirects to /. 