Working version - LDAP + Spring Boot

This commit is contained in:
corsoft
2014-06-15 13:17:38 +01:00
parent cc15245e4d
commit 81b4925a5e
17 changed files with 313 additions and 409 deletions

View File

@@ -0,0 +1,27 @@
package org.baeldung;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
/**
* Main Application Class - uses Spring Boot. Just run this as a normal Java
* class to run up a Jetty Server (on http://localhost:8080)
*
*/
@EnableAutoConfiguration
@ComponentScan("org.baeldung")
public class SampleLDAPApplication extends WebMvcConfigurerAdapter {
public static void main(String[] args) {
SpringApplication.run(SampleLDAPApplication.class, args);
}
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/login").setViewName("login");
}
}

View File

@@ -1,15 +0,0 @@
package org.baeldung.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class HomeController {
@RequestMapping("/homepage.html")
public @ResponseBody String index() {
return "homepage";
}
}

View File

@@ -0,0 +1,74 @@
package org.baeldung.controller;
import java.security.Principal;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* Spring Controller Definitions.
*/
@Controller
public class MyController {
@RequestMapping("/")
public String init(Map<String, Object> model, Principal principal) {
model.put("title", "PUBLIC AREA");
model.put("message", "Any user can view this page");
model.put("username", getUserName(principal));
model.put("userroles", getUserRoles(principal));
return "home";
}
@RequestMapping("/secure")
public String secure(Map<String, Object> model, Principal principal) {
model.put("title", "SECURE AREA");
model.put("message", "Only Authorised Users Can See This Page");
model.put("username", getUserName(principal));
model.put("userroles", getUserRoles(principal));
return "home";
}
private String getUserName(Principal principal){
if(principal == null){
return "anonymous";
}else{
final UserDetails currentUser = (UserDetails) ((Authentication) principal).getPrincipal();
Collection<? extends GrantedAuthority> authorities = currentUser.getAuthorities();
for(GrantedAuthority grantedAuthority : authorities) {
System.out.println(grantedAuthority.getAuthority());
}
return principal.getName();
}
}
private Collection<String> getUserRoles(Principal principal){
if(principal == null){
return Arrays.asList("none");
}else{
Set<String> roles = new HashSet<String>();
final UserDetails currentUser = (UserDetails) ((Authentication) principal).getPrincipal();
Collection<? extends GrantedAuthority> authorities = currentUser.getAuthorities();
for(GrantedAuthority grantedAuthority : authorities) {
roles.add(grantedAuthority.getAuthority());
}
return roles;
}
}
}

View File

@@ -0,0 +1,51 @@
package org.baeldung.security;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
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.stereotype.Controller;
/**
* Security Configuration - LDAP and HTTP Authorizations.
*/
@EnableAutoConfiguration
@ComponentScan
@Controller
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth)
throws Exception {
auth.ldapAuthentication()
.userSearchBase("ou=people")
.userSearchFilter("(uid={0})")
.groupSearchBase("ou=groups")
.groupSearchFilter("member={0}")
.contextSource()
.root("dc=baeldung,dc=com")
.ldif("classpath:users.ldif");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/home").permitAll()
.anyRequest().authenticated();
http
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.logoutSuccessUrl("/");
}
}

View File

@@ -1,17 +0,0 @@
package org.baeldung.spring;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan
@EnableAutoConfiguration
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}

View File

@@ -1,29 +0,0 @@
package org.baeldung.spring;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.servlet.configuration.EnableWebMvcSecurity;
@Configuration
@EnableWebMvcSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth)
throws Exception {
auth.ldapAuthentication()
.userSearchBase("ou=people")
.userSearchFilter("(uid={0})")
.groupSearchBase("ou=groups")
.groupSearchFilter("member={0}")
.contextSource()
.root("dc=baeldung,dc=com")
.ldif("classpath:users.ldif");
}
}

View File

@@ -10,9 +10,11 @@
<logger name="org.springframework" level="WARN" />
<logger name="org.springframework.transaction" level="WARN" />
<!-- in order to debug some marshalling issues, this needs to be TRACE -->
<logger name="org.springframework.web.servlet.mvc" level="WARN" />
<logger name="org.springframework.boot" level="WARN" />
<logger name="org.springframework.security" level="WARN" />
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,32 @@
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Error</title>
<link rel="stylesheet" th:href="@{/css/bootstrap.min.css}"
href="../../css/bootstrap.min.css" />
</head>
<body>
<div class="container">
<div class="navbar">
<div class="navbar-inner">
<a class="brand" href="http://www.thymeleaf.org"> Thymeleaf -
Plain </a>
<ul class="nav">
<li><a th:href="@{/}" href="home.html"> Home </a></li>
<li><a th:href="@{/secure}" href="secure.html"> Secure Page </a></li>
</ul>
</div>
</div>
<h1 th:text="${title}"></h1>
<div id="created" th:text="${#dates.format(timestamp)}"></div>
<div>
There was an unexpected error (type=<span th:text="${error}">Bad</span>, status=<span th:text="${status}">500</span>).
</div>
<div th:text="${message}">Fake content</div>
<div>
Please contact the operator with the above information.
</div>
</div>
</body>
</html>

View File

@@ -0,0 +1,37 @@
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title th:text="${title}">Title</title>
<link rel="stylesheet" th:href="@{/css/bootstrap.min.css}"
href="../../css/bootstrap.min.css" />
</head>
<body>
<div class="container">
<div class="navbar">
<div class="navbar-inner">
<a class="brand" href="http://www.thymeleaf.org"> Thymeleaf -
Plain </a>
<ul class="nav">
<li><a th:href="@{/}" href="home.html"> Home </a></li>
<li><a th:href="@{/secure}" href="home.html"> Secure Page </a></li>
</ul>
</div>
</div>
<div id="content">
<p>
<h1 th:text="${title}"></h1>
<h2 th:text="${message}"></h2>
</p>
</div>
<div id="footer">
<p>
Logged in as: <span th:text="${username}"></span>, Roles: <span th:text="${userroles}"></span>
</p>
</div>
</div>
</body>
</html>

View File

@@ -0,0 +1,36 @@
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Login</title>
<link rel="stylesheet" th:href="@{/css/bootstrap.min.css}"
href="../../css/bootstrap.min.css" />
</head>
<body onload="document.f.username.focus();">
<div class="container">
<div class="navbar">
<div class="navbar-inner">
<a class="brand" href="http://www.thymeleaf.org"> Thymeleaf -
Plain </a>
<ul class="nav">
<li><a th:href="@{/}" href="home.html"> Home </a></li>
<li><a th:href="@{/secure}" href="home.html"> Secure Page </a></li>
</ul>
</div>
</div>
<div class="content">
<p th:if="${param.logout}" class="alert">You have been logged out</p>
<p th:if="${param.error}" class="alert alert-error">There was an error, please try again</p>
<h2>Login with Username and Password</h2>
<form name="form" th:action="@{/login}" action="/login" method="POST">
<fieldset>
<input type="text" name="username" value="" placeholder="Username" />
<input type="password" name="password" placeholder="Password" />
</fieldset>
<input type="submit" id="login" value="Login"
class="btn btn-primary" />
</form>
</div>
</div>
</body>
</html>

View File

@@ -1,3 +1,8 @@
dn: ou=groups,dc=baeldung,dc=com
objectclass: top
objectclass: organizationalUnit
ou: groups
dn: ou=people,dc=baeldung,dc=com
objectclass: top
objectclass: organizationalUnit
@@ -8,7 +13,19 @@ objectclass: top
objectclass: person
objectclass: organizationalPerson
objectclass: inetOrgPerson
cn: David Lightman
sn: Lightman
cn: Jim Beam
sn: Beam
uid: baeldung
userPassword: password
userPassword: password
dn: cn=admin,ou=groups,dc=baeldung,dc=com
objectclass: top
objectclass: groupOfNames
cn: admin
member: uid=baeldung,ou=people,dc=baeldung,dc=com
dn: cn=user,ou=groups,dc=baeldung,dc=com
objectclass: top
objectclass: groupOfNames
cn: user
member: uid=baeldung,ou=people,dc=baeldung,dc=com

View File

@@ -1,34 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
xsi:schemaLocation="
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.2.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
<http pattern="/securityNone" security="none" />
<http use-expressions="true">
<intercept-url pattern="/**" access="isAuthenticated()" />
<http-basic entry-point-ref="myBasicAuthenticationEntryPoint" />
</http>
<!--
<authentication-manager />
<authentication-manager>
<authentication-provider>
<user-service>
<user name="user1" password="user1Pass" authorities="ROLE_USER" />
</user-service>
</authentication-provider>
</authentication-manager>
-->
<authentication-manager alias="authenticationManager">
<authentication-provider user-service-ref="securityConfig">
</authentication-provider>
</authentication-manager>
</beans:beans>

View File

@@ -1,5 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
</beans>

View File

@@ -1,7 +0,0 @@
<html>
<head></head>
<body>
<h1>This is the body of the sample view</h1>
</body>
</html>

View File

@@ -1,36 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>Spring Security Basic Auth Application</display-name>
<context-param>
<param-name>contextClass</param-name>
<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>org.baeldung.spring</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>mvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>