Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow basic authentication to authorize API access #1713

Merged
merged 7 commits into from
Oct 18, 2020
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/**
* Copyright (c) 2010-2020 Contributors to the openHAB project
*
* See the NOTICE file(s) distributed with this work for additional
* information.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.openhab.core.io.rest.auth.internal;

import java.security.Principal;

import javax.ws.rs.core.SecurityContext;

import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.openhab.core.auth.Role;

/**
* This {@link SecurityContext} can be used to give anonymous users (i.e. unauthenticated requests) the "user" role.
*
* @author Yannick Schaus - initial contribution
*/
@NonNullByDefault
public class AnonymousUserSecurityContext implements SecurityContext {

@Override
public @Nullable Principal getUserPrincipal() {
return null;
}

@Override
public boolean isUserInRole(@Nullable String role) {
return role == null || Role.USER.equals(role);
}

@Override
public boolean isSecure() {
return false;
}

@Override
public @Nullable String getAuthenticationScheme() {
return null;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@
package org.openhab.core.io.rest.auth.internal;

import java.io.IOException;
import java.util.Base64;
import java.util.Map;

import javax.annotation.Priority;
import javax.security.sasl.AuthenticationException;
Expand All @@ -25,44 +27,105 @@
import javax.ws.rs.core.SecurityContext;
import javax.ws.rs.ext.Provider;

import org.eclipse.jdt.annotation.Nullable;
import org.openhab.core.auth.Authentication;
import org.openhab.core.auth.User;
import org.openhab.core.auth.UserRegistry;
import org.openhab.core.auth.UsernamePasswordCredentials;
import org.openhab.core.config.core.ConfigurableService;
import org.openhab.core.io.rest.JSONResponse;
import org.openhab.core.io.rest.RESTConstants;
import org.osgi.framework.Constants;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Modified;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.jaxrs.whiteboard.JaxrsWhiteboardConstants;
import org.osgi.service.jaxrs.whiteboard.propertytypes.JaxrsApplicationSelect;
import org.osgi.service.jaxrs.whiteboard.propertytypes.JaxrsExtension;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
* This filter is responsible for parsing a token provided with a request, and hydrating a {@link SecurityContext} from
* the claims contained in the token.
* This filter is responsible for parsing credentials provided with a request, and hydrating a {@link SecurityContext}
* from these credentials if they are valid.
*
* @author Yannick Schaus - initial contribution
* @author Yannick Schaus - Allow basic authentication
*/
@PreMatching
@Component
@Component(configurationPid = "org.openhab.restauth", property = Constants.SERVICE_PID + "=org.openhab.restauth")
@ConfigurableService(category = "system", label = "API Security", description_uri = AuthFilter.CONFIG_URI)
@JaxrsExtension
@JaxrsApplicationSelect("(" + JaxrsWhiteboardConstants.JAX_RS_NAME + "=" + RESTConstants.JAX_RS_NAME + ")")
@Priority(Priorities.AUTHENTICATION)
@Provider
public class AuthFilter implements ContainerRequestFilter {
private final Logger logger = LoggerFactory.getLogger(AuthFilter.class);

private static final String ALT_AUTH_HEADER = "X-OPENHAB-TOKEN";

protected static final String CONFIG_URI = "system:restauth";
private static final String CONFIG_ALLOW_BASIC_AUTH = "allowBasicAuth";
private static final String CONFIG_IMPLICIT_USER_ROLE = "implicitUserRole";

private boolean allowBasicAuth = false;
private boolean implicitUserRole = true;

@Reference
private JwtHelper jwtHelper;

@Reference
private UserRegistry userRegistry;

@Activate
protected void activate(Map<String, Object> config) {
modified(config);
}

@Modified
protected void modified(@Nullable Map<String, @Nullable Object> properties) {
if (properties != null) {
Object value = properties.get(CONFIG_ALLOW_BASIC_AUTH);
allowBasicAuth = value != null && "true".equals(value.toString());
value = properties.get(CONFIG_IMPLICIT_USER_ROLE);
implicitUserRole = value == null || !"false".equals(value.toString());
}
}

@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
try {
String authHeader = requestContext.getHeaderString(HttpHeaders.AUTHORIZATION);
if (authHeader != null) {
String[] authParts = authHeader.split(" ");
if (authParts.length == 2) {
if ("Bearer".equals(authParts[0])) {
if ("Bearer".equalsIgnoreCase(authParts[0])) {
Authentication auth = jwtHelper.verifyAndParseJwtAccessToken(authParts[1]);
requestContext.setSecurityContext(new JwtSecurityContext(auth));
return;
} else if ("Basic".equalsIgnoreCase(authParts[0])) {
if (!allowBasicAuth) {
throw new AuthenticationException("Basic authentication is not allowed");
}
try {
String[] decodedCredentials = new String(Base64.getDecoder().decode(authParts[1]), "UTF-8")
.split(":");
if (decodedCredentials.length != 2) {
throw new AuthenticationException("Invalid Basic authentication credential format");
}
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(
decodedCredentials[0], decodedCredentials[1]);
Authentication auth = userRegistry.authenticate(credentials);
User user = userRegistry.get(auth.getUsername());
if (user == null) {
throw new org.openhab.core.auth.AuthenticationException("User not found in registry");
}
requestContext.setSecurityContext(new UserSecurityContext(user, "Basic"));
return;
} catch (org.openhab.core.auth.AuthenticationException e) {
throw new AuthenticationException("Invalid Basic authentication credentials", e);
}
}
}
}
Expand All @@ -73,8 +136,14 @@ public void filter(ContainerRequestContext requestContext) throws IOException {
requestContext.setSecurityContext(new JwtSecurityContext(auth));
return;
}

if (implicitUserRole) {
requestContext.setSecurityContext(new AnonymousUserSecurityContext());
}

} catch (AuthenticationException e) {
requestContext.abortWith(JSONResponse.createErrorResponse(Status.UNAUTHORIZED, "Invalid token"));
logger.warn("Unauthorized API request: {}", e.getMessage());
requestContext.abortWith(JSONResponse.createErrorResponse(Status.UNAUTHORIZED, "Invalid credentials"));
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.ext.Provider;

import org.openhab.core.auth.Role;
import org.openhab.core.io.rest.JSONResponse;
import org.openhab.core.io.rest.RESTConstants;
import org.osgi.service.component.annotations.Component;
Expand Down Expand Up @@ -115,15 +114,7 @@ private static class RolesAllowedRequestFilter implements ContainerRequestFilter
@Override
public void filter(final ContainerRequestContext requestContext) throws IOException {
if (!denyAll) {
// TODO: temporarily, until the complete authorization story is implemented, we consider operations
// allowed for user roles to be permitted unrestricted (even to unauthenticated users)
if (Arrays.asList(rolesAllowed).contains(Role.USER)) {
return;
}

if (rolesAllowed.length > 0 && !isAuthenticated(requestContext)) {
requestContext.abortWith(
JSONResponse.createErrorResponse(Status.UNAUTHORIZED, "User is not authenticated"));
if (rolesAllowed.length == 0) {
return;
}

Expand All @@ -134,8 +125,13 @@ public void filter(final ContainerRequestContext requestContext) throws IOExcept
}
}

requestContext.abortWith(JSONResponse.createErrorResponse(Status.FORBIDDEN,
"User is authenticated but doesn't have access to this resource"));
if (!isAuthenticated(requestContext)) {
requestContext
.abortWith(JSONResponse.createErrorResponse(Status.UNAUTHORIZED, "Authentication required"));
return;
}

requestContext.abortWith(JSONResponse.createErrorResponse(Status.FORBIDDEN, "Access denied"));
}

private static boolean isAuthenticated(final ContainerRequestContext requestContext) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
/**
* Copyright (c) 2010-2020 Contributors to the openHAB project
*
* See the NOTICE file(s) distributed with this work for additional
* information.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.openhab.core.io.rest.auth.internal;

import java.security.Principal;

import javax.ws.rs.core.SecurityContext;

import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.openhab.core.auth.User;

/**
* This {@link SecurityContext} contains information about a user, roles and authorizations granted to a client
* from a {@link User} instance.
*
* @author Yannick Schaus - initial contribution
*/
@NonNullByDefault
public class UserSecurityContext implements SecurityContext {

private User user;
private String authenticationScheme;

/**
* Constructs a security context from an instance of {@link User}
*
* @param user the user
* @param authenticationScheme the scheme that was used to authenticate the user, e.g. "Basic"
*/
public UserSecurityContext(User user, String authenticationScheme) {
this.user = user;
this.authenticationScheme = authenticationScheme;
}

@Override
public Principal getUserPrincipal() {
return user;
}

@Override
public boolean isUserInRole(@Nullable String role) {
return user.getRoles().contains(role);
}

@Override
public boolean isSecure() {
return true;
}

@Override
public String getAuthenticationScheme() {
return authenticationScheme;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?xml version="1.0" encoding="UTF-8"?>
<config-description:config-descriptions
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:config-description="https://openhab.org/schemas/config-description/v1.0.0"
xsi:schemaLocation="https://openhab.org/schemas/config-description/v1.0.0 https://openhab.org/schemas/config-description-1.0.0.xsd">

<config-description uri="system:restauth">
<parameter name="allowBasicAuth" type="boolean" required="false">
<label>Allow Basic Authentication</label>
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe add default=false here, just to make it clear what is used when not being set?

<default>false</default>
<description>Allow the use of Basic authentication to access protected API resources, in addition to access tokens
and API tokens.</description>
</parameter>
<parameter name="implicitUserRole" type="boolean" required="false">
<advanced>true</advanced>
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe add default=true here, just to make it clear what is used when not being set?

<label>Implicit user role for unauthenticated requests</label>
<default>true</default>
<description>By default, operations requiring the "user" role are available when unauthenticated. Disabling this
option will enforce authorization for these operations. Warning: this will cause clients which don't
support
authorization to break.</description>
kaikreuzer marked this conversation as resolved.
Show resolved Hide resolved
</parameter>
</config-description>

</config-description:config-descriptions>