[BAEL-9552] - Create spring-security-modules folder

This commit is contained in:
catalin-burcea
2019-12-13 13:04:59 +02:00
parent f9f1534394
commit d90a0a4fbb
712 changed files with 1140 additions and 1141 deletions
@@ -0,0 +1,25 @@
package com.baeldung.monitoring;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.Slf4jReporter;
public final class MetricRegistrySingleton {
public static final MetricRegistry metrics = new MetricRegistry();
static {
Logger logger = LoggerFactory.getLogger("org.baeldung.monitoring");
final Slf4jReporter reporter = Slf4jReporter.forRegistry(metrics).outputTo(logger).convertRatesTo(TimeUnit.SECONDS).convertDurationsTo(TimeUnit.MILLISECONDS).build();
reporter.start(5, TimeUnit.MINUTES);
}
private MetricRegistrySingleton() {
throw new AssertionError();
}
}
@@ -0,0 +1,94 @@
package com.baeldung.security;
import java.io.IOException;
import java.util.Collection;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.WebAttributes;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
public class MySimpleUrlAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
protected final Log logger = LogFactory.getLog(this.getClass());
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
public MySimpleUrlAuthenticationSuccessHandler() {
super();
}
// API
@Override
public void onAuthenticationSuccess(final HttpServletRequest request, final HttpServletResponse response, final Authentication authentication) throws IOException {
handle(request, response, authentication);
clearAuthenticationAttributes(request);
}
// IMPL
protected void handle(final HttpServletRequest request, final HttpServletResponse response, final Authentication authentication) throws IOException {
final String targetUrl = determineTargetUrl(authentication);
if (response.isCommitted()) {
logger.debug("Response has already been committed. Unable to redirect to " + targetUrl);
return;
}
redirectStrategy.sendRedirect(request, response, targetUrl);
}
protected String determineTargetUrl(final Authentication authentication) {
boolean isUser = false;
boolean isAdmin = false;
final Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
for (final GrantedAuthority grantedAuthority : authorities) {
if (grantedAuthority.getAuthority().equals("ROLE_USER")) {
isUser = true;
break;
} else if (grantedAuthority.getAuthority().equals("ROLE_ADMIN")) {
isAdmin = true;
break;
}
}
if (isUser) {
return "/homepage.html";
} else if (isAdmin) {
return "/console.html";
} else {
throw new IllegalStateException();
}
}
/**
* Removes temporary authentication-related data which may have been stored in the session
* during the authentication process.
*/
protected final void clearAuthenticationAttributes(final HttpServletRequest request) {
final HttpSession session = request.getSession(false);
if (session == null) {
return;
}
session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
}
public void setRedirectStrategy(final RedirectStrategy redirectStrategy) {
this.redirectStrategy = redirectStrategy;
}
protected RedirectStrategy getRedirectStrategy() {
return redirectStrategy;
}
}
@@ -0,0 +1,12 @@
package com.baeldung.session;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringSessionApplication {
public static void main(String[] args) {
SpringApplication.run(SpringSessionApplication.class, args);
}
}
@@ -0,0 +1,5 @@
package com.baeldung.session.bean;
public class Constants {
public static final String FOO = "foo";
}
@@ -0,0 +1,29 @@
package com.baeldung.session.bean;
import static org.springframework.context.annotation.ScopedProxyMode.TARGET_CLASS;
import static org.springframework.web.context.WebApplicationContext.SCOPE_SESSION;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
@Component
@Scope(value = SCOPE_SESSION, proxyMode = TARGET_CLASS)
public class Foo {
private final String created;
public Foo() {
this.created = LocalDateTime.now()
.format(DateTimeFormatter.ISO_DATE_TIME);
}
public Foo(Foo theFoo) {
this.created = theFoo.created;
}
public String getCreated() {
return created;
}
}
@@ -0,0 +1,45 @@
package com.baeldung.session.filter;
import java.io.IOException;
import java.util.Arrays;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class SessionFilter implements Filter{
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("init filter");
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
Cookie[] allCookies = req.getCookies();
if (allCookies != null) {
Cookie session = Arrays.stream(allCookies).filter(x -> x.getName().equals("JSESSIONID")).findFirst().orElse(null);
if (session != null) {
session.setHttpOnly(true);
session.setSecure(true);
res.addCookie(session);
}
}
chain.doFilter(req, res);
}
@Override
public void destroy() {
System.out.println("destroy filter");
}
}
@@ -0,0 +1,78 @@
package com.baeldung.session.security.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.session.HttpSessionEventPublisher;
import com.baeldung.security.MySimpleUrlAuthenticationSuccessHandler;
@Configuration
// @ImportResource({ "classpath:webSecurityConfig.xml" })
public class SecSecurityConfig extends WebSecurityConfigurerAdapter {
public SecSecurityConfig() {
super();
}
@Override
protected void configure(final AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth.inMemoryAuthentication()
.withUser("user1").password(passwordEncoder().encode("user1Pass")).roles("USER")
.and()
.withUser("admin1").password(passwordEncoder().encode("admin1Pass")).roles("ADMIN");
// @formatter:on
}
@Override
protected void configure(final HttpSecurity http) throws Exception {
// @formatter:off
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/anonymous*").anonymous()
.antMatchers("/login*","/invalidSession*", "/sessionExpired*", "/foo/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login.html")
.loginProcessingUrl("/login")
.successHandler(successHandler())
.failureUrl("/login.html?error=true")
.and()
.logout().deleteCookies("JSESSIONID")
.and()
.rememberMe().key("uniqueAndSecret").tokenValiditySeconds(86400)
.and()
.sessionManagement()
.sessionFixation().migrateSession()
.sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
.invalidSessionUrl("/invalidSession.html")
.maximumSessions(2)
.expiredUrl("/sessionExpired.html");
// @formatter:on
}
private AuthenticationSuccessHandler successHandler() {
return new MySimpleUrlAuthenticationSuccessHandler();
}
@Bean
public HttpSessionEventPublisher httpSessionEventPublisher() {
return new HttpSessionEventPublisher();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
@@ -0,0 +1,44 @@
package com.baeldung.session.web;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import com.baeldung.session.bean.Constants;
import com.baeldung.session.bean.Foo;
@RestController
@RequestMapping(path = "/foo")
public class FooController {
@Autowired
private Foo theFoo;
@GetMapping(path = "set")
public void fooSet(HttpSession session) {
session.setAttribute(Constants.FOO, new Foo());
}
@GetMapping(path = "autowired")
public Foo getAutowired() {
return new Foo(theFoo);
}
@GetMapping(path = "inject")
public Foo fooInject(HttpSession session) {
return (Foo) session.getAttribute(Constants.FOO);
}
@GetMapping(path = "raw")
public Foo fromRaw() {
ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
HttpSession session = attr.getRequest()
.getSession(true);
return (Foo) session.getAttribute(Constants.FOO);
}
}
@@ -0,0 +1,15 @@
package com.baeldung.session.web;
import javax.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class SessionRestController {
@GetMapping("/session-max-interval")
public String retrieveMaxSessionInactiveInterval(HttpSession session) {
return "Max Inactive Interval before Session expires: " + session.getMaxInactiveInterval();
}
}
@@ -0,0 +1,33 @@
package com.baeldung.session.web.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class MvcConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(final ViewControllerRegistry registry) {
registry.addViewController("/anonymous.html");
registry.addViewController("/login.html");
registry.addViewController("/homepage.html");
registry.addViewController("/sessionExpired.html");
registry.addViewController("/invalidSession.html");
registry.addViewController("/console.html");
}
/*
* Spring Boot supports configuring a ViewResolver with properties
*/
// @Bean
// public ViewResolver viewResolver() {
// final InternalResourceViewResolver bean = new InternalResourceViewResolver();
//
// bean.setViewClass(JstlView.class);
// bean.setPrefix("/WEB-INF/view/");
// bean.setSuffix(".jsp");
// }
}
@@ -0,0 +1,42 @@
package com.baeldung.web;
import java.util.concurrent.atomic.AtomicInteger;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import com.baeldung.monitoring.MetricRegistrySingleton;
import com.codahale.metrics.Counter;
public class SessionListenerWithMetrics implements HttpSessionListener {
private final AtomicInteger activeSessions;
private final Counter counterOfActiveSessions;
public SessionListenerWithMetrics() {
super();
activeSessions = new AtomicInteger();
counterOfActiveSessions = MetricRegistrySingleton.metrics.counter("web.sessions.active.count");
}
// API
public final int getTotalActiveSession() {
return activeSessions.get();
}
@Override
public final void sessionCreated(final HttpSessionEvent event) {
activeSessions.incrementAndGet();
counterOfActiveSessions.inc();
}
@Override
public final void sessionDestroyed(final HttpSessionEvent event) {
activeSessions.decrementAndGet();
counterOfActiveSessions.dec();
}
}