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

WIP: addition of module for jwt and kerberos #51

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all 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
2 changes: 2 additions & 0 deletions modules/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@
<module>cxf-server-rest</module>
<module>cxf-server-ws</module>
<module>security</module>
<module>security-jwt</module>
<module>security-kerberos</module>
<module>jpa-basic</module>
<module>jpa-dao</module>
<module>jpa-envers</module>
Expand Down
102 changes: 102 additions & 0 deletions modules/security-jwt/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.devonfw.java.dev</groupId>
<artifactId>devon4j-modules</artifactId>
<version>dev-SNAPSHOT</version>
</parent>
<groupId>com.devonfw.java.modules</groupId>
<artifactId>security-jwt</artifactId>
<version>${devon4j.version}</version>
<packaging>jar</packaging>
<name>${project.artifactId}</name>
<description>Security Module of the Open Application Standard Platform for Java (devon4j) specifically for jwt.</description>

<dependencies>
<!-- https://mvnrepository.com/artifact/io.jsonwebtoken/jjwt -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
Copy link
Member

Choose a reason for hiding this comment

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

I was using https://mvnrepository.com/artifact/org.springframework.security/spring-security-jwt so far. I assume however this is quite exchangeable.

<version>0.7.0</version>
Copy link
Member

Choose a reason for hiding this comment

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

We should always move versions to dependencyManagement in our BOM (to bring this also to the projects and avoid redundancy)

</dependency>
<!-- Spring Web & Servlet necessary for Request Filters -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<scope>provided</scope>
</dependency>

<!-- Spring Security -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
</dependency>

<!-- JSR 330 -->
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
</dependency>
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
</dependency>
<!-- JAXB -->
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<optional>true</optional>
</dependency>

<!-- Used by JsonUsernamePasswordAuthenticationFilter -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>

<!-- Test Dependencies -->
<dependency>
<groupId>com.devonfw.java.modules</groupId>
<artifactId>devon4j-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>devon4j-logging</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<profiles>
<profile>
<id>java9</id>
<activation>
<jdk>[9,12]</jdk>
</activation>
<dependencies>
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-runtime</artifactId>
</dependency>
<dependency>
<groupId>javax.activation</groupId>
<artifactId>javax.activation-api</artifactId>
</dependency>
</dependencies>
</profile>
Copy link
Member

Choose a reason for hiding this comment

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

Nice that you care about Java9+. However, we should address this more general in our parent POM of the modules as this more or less applies to all modules. Or to even go further, we should simply include these dependencies independent of the JDK version.
For your info:

  • We are using flatten plugin that will remove this profile anyway and embed dependency depending on the JVM used in our build and release process.
  • You can also define open version ranges. Limiting this to Java 12 seems kind of a random decision to me.

Copy link
Member

Choose a reason for hiding this comment

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

So to summarize: Simply add these dependencies as regular dependencies without profile. Support for Java8 is going to run out anyhow and the additional deps will not hurt. Benefit is that we create results that run on all JVMs (hopefully). See #16.

</profiles>
</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package com.devonfw.module.security.common;

public class AccountCredentials {
Copy link
Member

Choose a reason for hiding this comment

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

JavaDoc would be nice...

Copy link
Member

Choose a reason for hiding this comment

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

Can we just use an existing class for this (e.g. from Spring as this module is spring-specific anyhow)?


private String username;

private String password;

public String getUsername() {

return this.username;
}

public void setUsername(String username) {

this.username = username;
}

public String getPassword() {

return this.password;
}

public void setPassword(String password) {

this.password = password;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package com.devonfw.module.security.common;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.GenericFilterBean;

/**
* Filter for Json Web Tokens Authentication
*
*/
public class JWTAuthenticationFilter extends GenericFilterBean {
Copy link
Member

Choose a reason for hiding this comment

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


@SuppressWarnings("javadoc")
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
throws IOException, ServletException {

Authentication authentication = TokenAuthenticationService.getAuthentication((HttpServletRequest) request);

SecurityContextHolder.getContext().setAuthentication(authentication);
filterChain.doFilter(request, response);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package com.devonfw.module.security.common;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import com.fasterxml.jackson.databind.ObjectMapper;

/**
* Login Filter for Json Web Token
*
*/
public class JWTLoginFilter extends AbstractAuthenticationProcessingFilter {
Copy link
Member

Choose a reason for hiding this comment

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


/**
* The constructor.
*
* @param url the login url
* @param authManager the {@link AuthenticationManager}
*/
public JWTLoginFilter(String url, AuthenticationManager authManager) {

super(new AntPathRequestMatcher(url));
setAuthenticationManager(authManager);
}

@Override
public Authentication attemptAuthentication(HttpServletRequest req, HttpServletResponse res)
throws AuthenticationException, IOException, ServletException {

AccountCredentials creds = new ObjectMapper().readValue(req.getInputStream(), AccountCredentials.class);
Copy link
Member

Choose a reason for hiding this comment

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

Maybe I just do not understand this code but IMHO the JWT is send as an HTTP Authorization header behind the Bearer token scheme (OAuth standard). Seems I have to test and debug this...

return getAuthenticationManager()
.authenticate(new UsernamePasswordAuthenticationToken(creds.getUsername(), creds.getPassword()));
}

@Override
protected void successfulAuthentication(HttpServletRequest req, HttpServletResponse res, FilterChain chain,
Authentication auth) throws IOException, ServletException {

TokenAuthenticationService.addAuthentication(res, auth);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
package com.devonfw.module.security.common;

import javax.inject.Inject;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.csrf.CsrfFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
* @author snsarmok
Copy link
Member

Choose a reason for hiding this comment

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

We removed all @author tags from devon codebase. Please remove and instead add some JavaDoc sentence.

*
*/
public abstract class JwtWebSecurityConfig extends WebSecurityConfigurerAdapter {
@Value("${security.cors.enabled}")
boolean corsEnabled = true;

@Inject
private UserDetailsService userDetailsService;

@Inject
private PasswordEncoder passwordEncoder;

private CorsFilter getCorsFilter() {

UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("OPTIONS");
config.addAllowedMethod("HEAD");
config.addAllowedMethod("GET");
config.addAllowedMethod("PUT");
config.addAllowedMethod("POST");
config.addAllowedMethod("DELETE");
config.addAllowedMethod("PATCH");
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
Copy link
Member

Choose a reason for hiding this comment

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

To me this looks like redundancy and duplication of code. I am still uncertain about these CORS features we once added. However, we should keep them in a single place in the codebase.


/**
* Configure spring security to enable login with JWT.
*/
@Override
public void configure(HttpSecurity http) throws Exception {

String[] unsecuredResources = new String[] { "/login", "/security/**", "/services/rest/login",
"/services/rest/logout" };

http.userDetailsService(this.userDetailsService).csrf().disable().exceptionHandling().and().sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().authorizeRequests()
.antMatchers(unsecuredResources).permitAll().antMatchers(HttpMethod.POST, "/login").permitAll().anyRequest()
.authenticated().and()
// the api/login requests are filtered with the JWTLoginFilter
.addFilterBefore(new JWTLoginFilter("/login", authenticationManager()),
UsernamePasswordAuthenticationFilter.class)
// other requests are filtered to check the presence of JWT in header
.addFilterBefore(new JWTAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);

if (this.corsEnabled) {
http.addFilterBefore(getCorsFilter(), CsrfFilter.class);
}
Copy link
Member

Choose a reason for hiding this comment

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

So we should revisit this entire class. Shall we provide it at all? This is entirely unflexible. People that simply want to tweak a little aspect can not override it punctually. I once have written such a class where every little aspect is done by a single, well-named, protected method that allows proper tweaking.
However, I would in this case suggest to entirely remove this. Instead we should add some documentation how to integrate the module with spring security as well as creating a starter for spring-boot that does it automagically without interfering with the rest of your configs.

}

@Override
@SuppressWarnings("javadoc")
public void configure(AuthenticationManagerBuilder auth) throws Exception {

auth.inMemoryAuthentication().withUser("waiter").password(this.passwordEncoder.encode("waiter")).roles("Waiter")
.and().withUser("cook").password(this.passwordEncoder.encode("cook")).roles("Cook").and().withUser("barkeeper")
.password(this.passwordEncoder.encode("barkeeper")).roles("Barkeeper").and().withUser("chief")
.password(this.passwordEncoder.encode("chief")).roles("Chief");
Copy link
Member

Choose a reason for hiding this comment

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

This is misplaced in a module. It belongs to the sample app and end-users building devonfw apps do not want to have this in their productive app.

}

}
Loading