api key javaweb 应用代码举例
时间: 2024-03-16 08:42:29 浏览: 21
以下是一个简单的Java Web API应用示例,演示如何使用API Key进行身份验证和访问授权:
1. 定义API Key常量
```java
public class Constants {
public static final String API_KEY = "your_api_key_here";
}
```
2. 编写API访问控制Filter
```java
public class ApiKeyFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
String apiKey = request.getParameter("apiKey");
if (apiKey != null && apiKey.equals(Constants.API_KEY)) {
chain.doFilter(request, response);
} else {
HttpServletResponse httpResponse = (HttpServletResponse) response;
httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
}
}
@Override
public void destroy() {
}
}
```
3. 在web.xml中配置Filter
```xml
<filter>
<filter-name>ApiKeyFilter</filter-name>
<filter-class>com.example.ApiKeyFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>ApiKeyFilter</filter-name>
<url-pattern>/api/*</url-pattern>
</filter-mapping>
```
4. 编写API Controller
```java
@RestController
@RequestMapping("/api")
public class ApiController {
@GetMapping("/hello")
public String hello() {
return "Hello World!";
}
}
```
5. 在Controller中添加API Key访问控制
```java
@RestController
@RequestMapping("/api")
public class ApiController {
@GetMapping("/hello")
public String hello(@RequestParam("apiKey") String apiKey) {
if (apiKey.equals(Constants.API_KEY)) {
return "Hello World!";
} else {
throw new UnauthorizedException("Unauthorized");
}
}
}
```
这个示例演示了如何使用API Key进行身份验证和访问授权,当API访问时需要在请求参数中提供API Key,否则将返回401 Unauthorized错误。可以通过修改Constants类中的API_KEY常量来更改API Key的值。