-
-
Notifications
You must be signed in to change notification settings - Fork 415
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
Changes from 2 commits
46b5c2b
df00d2b
c862a8a
18818fe
58f8910
348677d
0c9d044
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
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 |
---|---|---|
|
@@ -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; | ||
|
@@ -25,33 +27,72 @@ | |
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_NO_UNAUTHENTICATED_USER_ROLE = "noUnauthenticatedUserRole"; | ||
|
||
private boolean allowBasicAuth = false; | ||
private boolean noUnauthenticatedUserRole = false; | ||
|
||
@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_NO_UNAUTHENTICATED_USER_ROLE); | ||
noUnauthenticatedUserRole = value != null && "true".equals(value.toString()); | ||
} | ||
} | ||
|
||
@Override | ||
public void filter(ContainerRequestContext requestContext) throws IOException { | ||
try { | ||
|
@@ -63,6 +104,28 @@ public void filter(ContainerRequestContext requestContext) throws IOException { | |
Authentication auth = jwtHelper.verifyAndParseJwtAccessToken(authParts[1]); | ||
requestContext.setSecurityContext(new JwtSecurityContext(auth)); | ||
return; | ||
} else if ("Basic".equals(authParts[0])) { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. A small suggestion here - it might be worth to use There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. @ghys This suggestion does not yet seem to be addressed. |
||
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); | ||
} | ||
} | ||
} | ||
} | ||
|
@@ -73,8 +136,14 @@ public void filter(ContainerRequestContext requestContext) throws IOException { | |
requestContext.setSecurityContext(new JwtSecurityContext(auth)); | ||
return; | ||
} | ||
|
||
if (!noUnauthenticatedUserRole) { | ||
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 |
---|---|---|
@@ -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,22 @@ | ||
<?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> | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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? |
||
<description>Allow the use of Basic authentication to access protected API resources.</description> | ||
</parameter> | ||
<parameter name="noUnauthenticatedUserRole" type="boolean" required="false"> | ||
<advanced>true</advanced> | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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>Deny unauthenticated access to user operations</label> | ||
<description>By default, operations requiring the "user" role are available when unauthenticated. Enabling this | ||
option will require authentication for these operations. Warning: this will cause clients which don't | ||
support | ||
authorization to break.</description> | ||
ghys marked this conversation as resolved.
Show resolved
Hide resolved
|
||
</parameter> | ||
</config-description> | ||
|
||
</config-description:config-descriptions> |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Argh, I am really getting a knot in my brain here (German proverb) by this double negation. How about changing this parameter to something like "enableAuthForUserResources"?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It was more to the tune of "prevent unauthenticated requests from getting an implicit user role in the security context", so I tried to rename it to "noImplicitUserRole" / "No implicit user role for unauthenticated requests", that's perhaps clearer. Still a double negation, so if you still disagree I'll change it to "enableAuthForUserResources" :)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
And if we change it to "ImplicitUserRole" and have default=true, knowing that on the long run our wish is to get the setting to OFF? It would be in line with the basic auth setting, i.e. enabling something means your system becomes less secure.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Good point, I insisted on having false as the default but that's not really a requirement.