I'm creating a bearer token for testing purposes with an endpoint but I get an error during the authorization and I think I miss something in the endpoint function.
Error in response: AuthenticationError { challenge: Bearer { scope: None, realm: None, error: None, error_description: None, error_uri: None }, status_code: 401 }
// This is the endpoint I want to test
#[get("/blacklight/{url}")]
pub async fn blacklight(
path: web::Path<String>,
claims: Option<web::ReqData<Claims>>
) -> impl Responder {
let url: String = path.into_inner();
match url_check::is_url(url.as_str()) {
true => {
if let Some(claims) = claims {
publish_service::publisher(claims.sub.clone(), &url);
}
HttpResponse::Ok().json("Ok")
},
false => HttpResponse::BadRequest().body("ProtocolError: Cannot navigate to invalid URL")
}
}
// This is the endpoint to create a test token
#[post("/createJWT")]
pub async fn encoder(claims: web::Json<Claims>) -> impl Responder {
let env: String = std::env::var("PRIV_KEY")
.expect("PRIV_KEY must be set.");
let read_from_file: String = std::fs::read_to_string(env).unwrap();
let key: &str = read_from_file.as_str();
let header: Header = Header::new(jsonwebtoken::Algorithm::ES256);
let token: String = encode(
&header,
&claims,
&EncodingKey::from_ec_pem(&key.as_bytes()).unwrap()
).unwrap();
info!("Encode new token...\n Token: {}", token.clone());
HttpResponse::Created().json(token.clone())
}
// This is my validation function
pub fn validate_token(token: &str) -> Result<jsonwebtoken::TokenData<Claims>, HttpResponse> {
let val: Validation = Validation::new(Algorithm::HS256);
let env: String = std::env::var("PUB_KEY")
.expect("PUB_KEY must be set.");
let pub_key: &[u8] = env.as_bytes();
let unauth: &str = "The access token provided is expired, revoked, malformed, or invalid";
let bad_req: &str = "The request has a invalid or missing parameter";
let bad_gate: &str = "The request can't be handled";
match decode::<Claims>(&token, &DecodingKey::from_ec_pem(pub_key).unwrap(), &val) {
Ok(c) => Ok(c),
Err(err) => match *err.kind() {
ErrorKind::InvalidToken => Err(HttpResponse::Unauthorized().body(unauth)),
ErrorKind::InvalidIssuer => Err(HttpResponse::BadRequest().body(bad_req)),
_ => Err(HttpResponse::BadGateway().body(bad_gate)),
},
}
}
async fn validator(
req: ServiceRequest,
credentials: BearerAuth,
) -> Result<ServiceRequest, (Error, ServiceRequest)> {
let config: bearer::Config = req.app_data::<bearer::Config>()
.cloned()
.unwrap_or_default()
.scope("urn:example:channel=HBO&urn:example:rating=G,PG-13");
match auth_service::validate_token(credentials.token()) {
Ok(res) => {
info!("Valid request");
req
.extensions_mut()
.insert(res.claims);
Ok(req)
},
Err(_) => Err((AuthenticationError::from(config).into(), req))
}
}