gpt4 book ai didi

Java JAX-RS 名称绑定(bind)不工作

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:11:20 26 4
gpt4 key购买 nike

我正在为我的 REST 服务开发身份验证过滤器。

谁能解释一下为什么这个名称绑定(bind)不起作用。

当我发出 post 请求时,我可以收到字符串“Tokenized”,但日志不会打印“Inside the filter”。

import java.io.IOException;
import java.lang.annotation.Retention;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.FormParam;
import javax.ws.rs.NameBinding;
import javax.ws.rs.Produces;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.TYPE;
import java.lang.annotation.Target;
import javax.annotation.Priority;
import javax.ws.rs.NotAuthorizedException;
import javax.ws.rs.Priorities;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.ext.Provider;
import org.apache.log4j.Logger;



@Path("/authentication")
public class AuthenticationHandler {

final static Logger log = Logger.getLogger(AuthenticationHandler.class);

@NameBinding
@Retention(RUNTIME)
@Target({TYPE, METHOD})
public @interface Secured {
}

@Secured
@Provider
@Priority(Priorities.AUTHENTICATION)
public class AuthenticationFilter implements ContainerRequestFilter {

@Override
public void filter(ContainerRequestContext requestContext) throws IOException {

log.info("Inside the filter");

// Get the HTTP Authorization header from the request
String authorizationHeader
= requestContext.getHeaderString(HttpHeaders.AUTHORIZATION);

// Check if the HTTP Authorization header is present and formatted correctly
if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) {
throw new NotAuthorizedException("Authorization header must be provided");
}

// Extract the token from the HTTP Authorization header
String token = authorizationHeader.substring("Bearer".length()).trim();

try {

// Validate the token
validateToken(token);

} catch (Exception e) {
requestContext.abortWith(
Response.status(Response.Status.UNAUTHORIZED).build());
}
}

private void validateToken(String token) throws Exception {
// Check if it was issued by the server and if it's not expired
// Throw an Exception if the token is invalid
}


}

@POST
@Secured
@Path("/request_token")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response authenticateUser(@FormParam("username") String username,
@FormParam("password") String password) {

try {

// Authenticate the user using the credentials provided
authenticate(username, password);

// Issue a token for the user
String token = issueToken(username);

// Return the token on the response
return Response.ok(token).build();

} catch (Exception e) {
return Response.status(Response.Status.UNAUTHORIZED).build();
}
}



private boolean authenticate(String username, String password) throws Exception {
return true;
}

private String issueToken(String username) {
return "Tokenized";
}

}

最佳答案

感谢小费 peeskillet。

在为 Name Bind 和 Filter 创建单独的类后,它现在工作正常。如果有人需要,我会在下面发布解决方案。

我现在的问题是,有没有办法将这两个类放在一个单独的包中,因为我尝试将它放在我的 Util 包中,但它无法正常工作。

peeskillet:再次感谢您的提示。

AuthenticationFilter.java

import com.binosaurs.sf.backend.handler.Secured;
import com.binosaurs.sf.backend.util.*;
import java.io.IOException;
import javax.annotation.Priority;
import javax.ws.rs.NotAuthorizedException;
import javax.ws.rs.Priorities;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.Provider;
import org.apache.log4j.Logger;



@Secured
@Provider
@Priority(Priorities.AUTHENTICATION)
public class AuthenticationFilter implements ContainerRequestFilter {

// Get Log4j Logger
final static Logger log = Logger.getLogger(AuthenticationFilter.class);

@Override
public void filter(ContainerRequestContext requestContext) throws IOException {

log.info("Inside the filter");

// Get the HTTP Authorization header from the request
String authorizationHeader
= requestContext.getHeaderString(HttpHeaders.AUTHORIZATION);

// Check if the HTTP Authorization header is present and formatted correctly
if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) {
throw new NotAuthorizedException("Authorization header must be provided");
}

// Extract the token from the HTTP Authorization header
String token = authorizationHeader.substring("Bearer".length()).trim();

try {

// Validate the token
validateToken(token);

} catch (Exception e) {
requestContext.abortWith(
Response.status(Response.Status.UNAUTHORIZED).build());
}
}

private void validateToken(String token) throws Exception {
// Check if it was issued by the server and if it's not expired
// Throw an Exception if the token is invalid
}


}

安全.java

    /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.binosaurs.sf.backend.handler;

import com.binosaurs.sf.backend.util.*;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.TYPE;
import java.lang.annotation.Retention;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Target;
import javax.ws.rs.NameBinding;

@NameBinding
@Retention(RUNTIME)
@Target({TYPE, METHOD})
public @interface Secured {
}

AuthenticationHandler.java

    package com.binosaurs.sf.backend.handler;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.FormParam;
import javax.ws.rs.Produces;
import org.apache.log4j.Logger;



@Path("/authentication")
public class AuthenticationHandler {

final static Logger log = Logger.getLogger(AuthenticationHandler.class);

@POST
@Secured
@Path("/request_token")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response authenticateUser(@FormParam("username") String username,
@FormParam("password") String password) {

try {

// Authenticate the user using the credentials provided
authenticate(username, password);

// Issue a token for the user
String token = issueToken(username);

// Return the token on the response
return Response.ok(token).build();

} catch (Exception e) {
return Response.status(Response.Status.UNAUTHORIZED).build();
}
}



private boolean authenticate(String username, String password) throws Exception {
return true;
}

private String issueToken(String username) {
return "Tokenized";
}

}

关于Java JAX-RS 名称绑定(bind)不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44615539/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com