Skip to content

Instantly share code, notes, and snippets.

@dwelch2344
Created June 10, 2012 21:17
Show Gist options
  • Save dwelch2344/2907360 to your computer and use it in GitHub Desktop.
Save dwelch2344/2907360 to your computer and use it in GitHub Desktop.
Spring Security & Expression Language Tutorial Gist
<security:intercept-url pattern="/secure/**" access="hasRole('ROLE_ADMIN')"/>
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Service;
@Service
@Secured("hasRole('ROLE_ADMIN')")
public class PersonService {
@Secured("hasRole('ROLE_ADMIN_WRITE')")
public void deletePerson(Long personId){
// ... delete them!
}
}
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>${spring.version}</version>
<scope>compile</scope>
<exclusions>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>${spring.version}</version>
<scope>compile</scope>
<exclusions>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>${spring.version}</version>
<exclusions>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:security="http://www.springframework.org/schema/security"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
">
<!-- Root Context: defines shared resources visible to all other web components -->
<import resource="db.xml" />
<bean id="org.springframework.security.authenticationManager"
class="org.springframework.security.authentication.ProviderManager">
<property name="providers">
<util:list>
<bean
class="com.example.security.HardCodedUserDetailsAuthentcationProvider">
<constructor-arg index="0" value="user" />
<constructor-arg index="1" value="password" />
</bean>
</util:list>
</property>
</bean>
<security:http entry-point-ref="authenticationProcessingFilterEntryPoint" use-expressions="true" auto-config="true">
<security:form-login login-processing-url="/doLogin" />
<security:anonymous enabled="false"/>
<security:intercept-url pattern="/secure/**" access="hasRole('ROLE_ADMIN')"/>
<!-- Uncomment this section to enable security -->
<!-- <security:intercept-url pattern="/**" access="isAuthenticated()" /> -->
</security:http>
<bean id="authenticationProcessingFilterEntryPoint"
class="org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint">
<property name="loginFormUrl" value="/login" />
</bean>
</beans>
package com.example.security;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
public class HardCodedUserDetailsAuthentcationProvider extends
AbstractUserDetailsAuthenticationProvider {
private Logger logger = Logger.getLogger(getClass().getName());
private final String username, password;
public HardCodedUserDetailsAuthentcationProvider(String username,
String password) {
super();
this.username = username;
this.password = password;
}
@Override
protected void additionalAuthenticationChecks(UserDetails userDetails,
UsernamePasswordAuthenticationToken authentication)
throws AuthenticationException {
logger.info(String
.format("additionalAuthenticationChecks requested on %s details with %s authentication",
userDetails, authentication));
}
@Override
protected UserDetails retrieveUser(String username,
UsernamePasswordAuthenticationToken authentication)
throws AuthenticationException {
Object creds = authentication.getCredentials();
if (creds != null && String.class.isAssignableFrom(creds.getClass())) {
String pw = (String) creds;
if (this.username.equalsIgnoreCase(username)
&& this.password.equals(pw)) {
boolean enabled = true, accountNonExpired = true, credentialsNonExpired = true, accountNonLocked = true;
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
authorities.add(new GrantedAuthorityImpl("ROLE_ADMIN"));
User user = new User(username, pw, enabled, accountNonExpired,
credentialsNonExpired, accountNonLocked, authorities);
return user;
}
throw new BadCredentialsException("Invalid credentials!!");
}
// creds should never be null, so we shouldn't ever end up here
throw new IllegalStateException("Unreachable code");
}
}
<!-- Spring Security filter chain -->
<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>
<%-- @taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" --%>
<%-- @taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" --%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="screen, projection" href="resources/tsp.css" />
<link rel="shortcut icon" type="image/ico" href="/favicon.ico" />
<script type="text/javascript" src="resources/ixf/scripts/jquery-1.4.2.min.js"></script>
</head>
<body>
<form action="doLogin" method="post" >
<label id="j_usernameLabel" for="j_username">Username: </label>
<input type="text" name="j_username" id="j_username" tabindex="1" autocomplete="off" />
<br/>
<label id="j_passwordLabel" for="j_password">Password: </label></dt>
<input type="password" name="j_password" id="j_password" tabindex="2" autocomplete="off" />
<br/>
<input id="j_submitButton" type="submit" value="Submit"/>
</form>
</body>
</html>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<html>
<head>
<title>Users</title>
</head>
<body>
<h1>
Users Page
</h1>
${controllerMessage}
</body>
</html>
package co.davidwelch.training.spring.mvc_el;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* Sample controller for going to the home page with a message
*/
@Controller
public class HomeController {
private static final Logger logger = LoggerFactory
.getLogger(HomeController.class);
/**
* Selects the home page and populates the model with a message
*/
@RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Model model) {
logger.info("Welcome home!");
model.addAttribute("controllerMessage",
"This is the message from the controller!");
return "home";
}
/**
* Displays the login page
*/
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String login(Model model) {
logger.info("Displaying Login page!");
return "login";
}
/**
* Displays the (secured) user page
*/
@RequestMapping(value = "/secure/users", method = RequestMethod.GET)
public String users(Model model) {
logger.info("Displaying Users page!");
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
// auth should never be null, but check just in case
String message = String.format("Welcome %s! This is the secure section", auth == null ? "null" : auth.getName());
model.addAttribute("controllerMessage", message );
return "users";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment