diff options
author | Alexander Alexeev | 2016-11-28 13:39:04 +0700 |
---|---|---|
committer | Alexander Alexeev | 2016-11-28 13:39:04 +0700 |
commit | bc23d2d2125d2086847397e85335f29a70668f6b (patch) | |
tree | 8c4f0ce7a91763eec65ce36559b7a6c388d9c68d | |
parent | 47a285e60b0780c7d81e4e1b77736f69e0aaf761 (diff) |
remember-me authorization with test; a statndard DaoAuthentication provider used
12 files changed, 239 insertions, 126 deletions
diff --git a/juick-api/src/main/java/com/juick/api/configuration/ApiSecurityConfig.java b/juick-api/src/main/java/com/juick/api/configuration/ApiSecurityConfig.java index b3d2d21e..8da51f5a 100644 --- a/juick-api/src/main/java/com/juick/api/configuration/ApiSecurityConfig.java +++ b/juick-api/src/main/java/com/juick/api/configuration/ApiSecurityConfig.java @@ -1,24 +1,27 @@ package com.juick.api.configuration; import com.juick.server.security.JuickAuthenticationEntryPoint; -import com.juick.server.security.JuickAuthenticationProvider; import com.juick.service.UserService; +import com.juick.service.security.JuickUserDetailsService; +import com.juick.service.security.SimpleRememberMeServices; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; import org.springframework.http.HttpMethod; +import org.springframework.security.authentication.dao.DaoAuthenticationProvider; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.http.SessionCreationPolicy; -import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; +import org.springframework.security.web.authentication.RememberMeServices; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.CorsConfigurationSource; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import javax.inject.Inject; import java.util.Arrays; +import java.util.concurrent.TimeUnit; /** * Created by aalexeev on 11/21/16. @@ -38,8 +41,7 @@ public class ApiSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { - http.addFilterBefore(getJuickHashFilter(), UsernamePasswordAuthenticationFilter.class) - .authorizeRequests() + http.authorizeRequests() .antMatchers(HttpMethod.OPTIONS).permitAll() .anyRequest().hasRole("USER") .and().httpBasic().authenticationEntryPoint(getJuickAuthenticationEntryPoint()) @@ -48,22 +50,42 @@ public class ApiSecurityConfig extends WebSecurityConfigurerAdapter { .and().servletApi() .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and().exceptionHandling().authenticationEntryPoint(getJuickAuthenticationEntryPoint()) - .and().authenticationProvider(new JuickAuthenticationProvider(userService)) + .and() + .rememberMe() + .alwaysRemember(true) + .tokenValiditySeconds((int) TimeUnit.DAYS.toSeconds(6 * 30)) + .rememberMeServices(rememberMeServices()) + .key(env.getProperty("auth_remember_me_key")) + .and().authenticationProvider(authenticationProvider()) .headers().defaultsDisabled().cacheControl(); } @Bean - public JuickAuthenticationEntryPoint getJuickAuthenticationEntryPoint() { - return new JuickAuthenticationEntryPoint(); + public DaoAuthenticationProvider authenticationProvider() { + DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider(); + + authenticationProvider.setUserDetailsService(userDetailsService()); + + return authenticationProvider; + } + + @Bean + public JuickUserDetailsService userDetailsService() { + return new JuickUserDetailsService(userService); + } + + @Bean + public RememberMeServices rememberMeServices() throws Exception { + return new SimpleRememberMeServices(env.getProperty("auth_remember_me_key"), userDetailsService(), userService, env); } @Bean - public JuickHashFilter getJuickHashFilter() { - return new JuickHashFilter(); + public JuickAuthenticationEntryPoint getJuickAuthenticationEntryPoint() { + return new JuickAuthenticationEntryPoint(); } @Bean - CorsConfigurationSource corsConfigurationSource() { + public CorsConfigurationSource corsConfigurationSource() { CorsConfiguration configuration = new CorsConfiguration(); configuration.setAllowedOrigins(Arrays.asList("*")); diff --git a/juick-api/src/main/java/com/juick/api/configuration/JuickHashFilter.java b/juick-api/src/main/java/com/juick/api/configuration/JuickHashFilter.java deleted file mode 100644 index 62e6f3d2..00000000 --- a/juick-api/src/main/java/com/juick/api/configuration/JuickHashFilter.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.juick.api.configuration; - -import com.juick.User; -import com.juick.service.UserService; -import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; -import org.springframework.security.core.GrantedAuthority; -import org.springframework.security.core.authority.SimpleGrantedAuthority; -import org.springframework.security.core.context.SecurityContext; -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.security.web.authentication.WebAuthenticationDetails; -import org.springframework.web.filter.GenericFilterBean; - -import javax.inject.Inject; -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletRequest; -import java.io.IOException; -import java.util.Collections; -import java.util.List; - -/** - * Created by vitalyster on 27.11.2016. - */ -public class JuickHashFilter extends GenericFilterBean { - @Inject - UserService userService; - - @Override - public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { - String hash = request.getParameter("hash"); - if (hash != null) { - User user = userService.getUserByHash(hash); - if (user.getUid() > 0) { - List<GrantedAuthority> authorities = Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER")); - UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user.getName(), null); - token.setDetails(new WebAuthenticationDetails((HttpServletRequest) request)); - SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(user.getName(), null, authorities)); - } - } - chain.doFilter(request, response); - } - } diff --git a/juick-api/src/test/java/com/juick/api/tests/MessagesTests.java b/juick-api/src/test/java/com/juick/api/tests/MessagesTests.java index 7f238b79..cec2bc7d 100644 --- a/juick-api/src/test/java/com/juick/api/tests/MessagesTests.java +++ b/juick-api/src/test/java/com/juick/api/tests/MessagesTests.java @@ -19,6 +19,7 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.context.annotation.Primary; import org.springframework.http.MediaType; +import org.springframework.security.crypto.codec.Base64; import org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @@ -28,7 +29,9 @@ import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import javax.inject.Inject; +import javax.servlet.http.Cookie; import java.util.Collections; +import java.util.Optional; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.is; @@ -150,7 +153,39 @@ public class MessagesTests { } @Test - public void homeTestWithSimpleCors() throws Exception { + public void homeTestWithMessagesAndRememberMe() throws Exception { + String ugnichName = "ugnich"; + String uginchPassword = "MyPassw0rd!"; + String msgText = "Привет, я - Угнич"; + String hash = "12345678"; + + User user = getUser(1, ugnichName, uginchPassword); + Message msg = getMessage(user, msgText); + + when(userService.getUserByName(ugnichName)) + .thenReturn(user); + when(userService.getUserByUID(1)) + .thenReturn(Optional.of(user)); + when(userService.getFullyUserByName(ugnichName)) + .thenReturn(user); + when(messagesService.getMyFeed(1, 0)) + .thenReturn(Collections.singletonList(1)); + when(messagesService.getMessages(Collections.singletonList(1))) + .thenReturn(Collections.singletonList(msg)); + when(userService.getUIDbyHash(hash)) + .thenReturn(1); + + Cookie cookie = new Cookie("hash", new String(Base64.encode(hash.getBytes()))); + cookie.setDomain("juick.com"); + cookie.setMaxAge(100); + + mockMvc.perform( + get("/home").cookie(cookie)) + .andExpect(status().isOk()); + } + + @Test + public void homeTestWithMEssagesAndSimpleCors() throws Exception { String ugnichName = "ugnich"; String uginchPassword = "MyPassw0rd!"; diff --git a/juick-api/src/test/resources/juick.conf.example b/juick-api/src/test/resources/juick.conf.example new file mode 100644 index 00000000..cca3c182 --- /dev/null +++ b/juick-api/src/test/resources/juick.conf.example @@ -0,0 +1,8 @@ +# The domain name for Web (default value - "juick.com") +web_domain=juick.com + +# Authority cookie name (default value - "hash") +auth_cookie_name=hash + +# Authority remember-me key +auth_remember_me_key=3vHcy3OUDQlkpRDm diff --git a/juick-server/src/main/java/com/juick/server/security/JuickAuthenticationProvider.java b/juick-server/src/main/java/com/juick/server/security/JuickAuthenticationProvider.java deleted file mode 100644 index 87908950..00000000 --- a/juick-server/src/main/java/com/juick/server/security/JuickAuthenticationProvider.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.juick.server.security; - -import com.juick.User; -import com.juick.server.security.entities.JuickUser; -import com.juick.service.UserService; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.security.authentication.AuthenticationProvider; -import org.springframework.security.authentication.LockedException; -import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.AuthenticationException; -import org.springframework.util.Assert; - -import javax.inject.Inject; - -/** - * Created by vitalyster on 25.11.2016. - */ -public class JuickAuthenticationProvider implements AuthenticationProvider { - private final Logger logger = LoggerFactory.getLogger(getClass()); - - private final UserService userService; - - @Inject - public JuickAuthenticationProvider(UserService userService) { - Assert.notNull(userService); - this.userService = userService; - } - - @Override - public Authentication authenticate(Authentication authentication) throws AuthenticationException { - String name = authentication.getName(); - String password = authentication.getCredentials().toString(); - - User user = userService.getFullyUserByName(name); - if (user != null) { - if (user.isBanned()) - throw new LockedException("Username \"" + name + "\" is banned"); - - return new UsernamePasswordAuthenticationToken(name, password, JuickUser.USER_AUTHORITY); - } - return null; - } - - @Override - public boolean supports(Class<?> authentication) { - return authentication.equals(UsernamePasswordAuthenticationToken.class); - } -} diff --git a/juick-server/src/main/java/com/juick/server/security/entities/JuickUser.java b/juick-server/src/main/java/com/juick/server/security/entities/JuickUser.java index 3e413bf6..f6d27ddf 100644 --- a/juick-server/src/main/java/com/juick/server/security/entities/JuickUser.java +++ b/juick-server/src/main/java/com/juick/server/security/entities/JuickUser.java @@ -28,7 +28,7 @@ public class JuickUser implements UserDetails { @Override public String getPassword() { - return null; + return user.getCredentials(); } @Override diff --git a/juick-server/src/main/java/com/juick/service/UserService.java b/juick-server/src/main/java/com/juick/service/UserService.java index 4d7d09c9..3fb2ae12 100644 --- a/juick-server/src/main/java/com/juick/service/UserService.java +++ b/juick-server/src/main/java/com/juick/service/UserService.java @@ -111,4 +111,8 @@ public interface UserService { EmailOpts getEmailOpts(User user); String getEmailHash(User user); + + int deleteLoginForUser(String name); + + int setLoginForUser(int uid, String loginHash); } diff --git a/juick-server/src/main/java/com/juick/service/UserServiceImpl.java b/juick-server/src/main/java/com/juick/service/UserServiceImpl.java index d1e4eff5..a00eab3f 100644 --- a/juick-server/src/main/java/com/juick/service/UserServiceImpl.java +++ b/juick-server/src/main/java/com/juick/service/UserServiceImpl.java @@ -37,6 +37,7 @@ public class UserServiceImpl extends BaseJdbcService implements UserService { user.setUid(rs.getInt(1)); user.setName(rs.getString(2)); user.setBanned(rs.getBoolean(3)); + user.setLang(rs.getString(4)); return user; } @@ -109,7 +110,7 @@ public class UserServiceImpl extends BaseJdbcService implements UserService { @Override public Optional<User> getUserByUID(final int uid) { List<User> list = getJdbcTemplate().query( - "SELECT id, nick,banned FROM users WHERE id = ?", new UserMapper(), uid); + "SELECT id, nick, banned, lang FROM users WHERE id = ?", new UserMapper(), uid); return list.isEmpty() ? Optional.empty() : Optional.of(list.get(0)); } @@ -121,7 +122,7 @@ public class UserServiceImpl extends BaseJdbcService implements UserService { if (StringUtils.isNotBlank(username)) { List<User> list = getJdbcTemplate().query( - "SELECT id, nick, banned FROM users WHERE nick = ?", new UserMapper(), username); + "SELECT id, nick, banned, lang FROM users WHERE nick = ?", new UserMapper(), username); if (!list.isEmpty()) result = list.get(0); @@ -169,7 +170,7 @@ public class UserServiceImpl extends BaseJdbcService implements UserService { if (StringUtils.isNotBlank(jid)) { List<User> list = getJdbcTemplate().query( - "SELECT id, nick, banned FROM users WHERE id = (SELECT user_id FROM jids WHERE jid = ?)", + "SELECT id, nick, banned, lang FROM users WHERE id = (SELECT user_id FROM jids WHERE jid = ?)", new UserMapper(), jid); @@ -186,7 +187,7 @@ public class UserServiceImpl extends BaseJdbcService implements UserService { return Collections.emptyList(); return getNamedParameterJdbcTemplate().query( - "SELECT id, nick, banned FROM users WHERE nick IN (:unames)", + "SELECT id, nick, banned, lang FROM users WHERE nick IN (:unames)", new MapSqlParameterSource("unames", unames), new UserMapper()); } @@ -198,7 +199,7 @@ public class UserServiceImpl extends BaseJdbcService implements UserService { return Collections.emptyList(); return getNamedParameterJdbcTemplate().query( - "SELECT id, nick, banned FROM users WHERE id IN (:ids)", + "SELECT id, nick, banned, lang FROM users WHERE id IN (:ids)", new MapSqlParameterSource("ids", uids), new UserMapper()); } @@ -273,7 +274,7 @@ public class UserServiceImpl extends BaseJdbcService implements UserService { public com.juick.User getUserByHash(final String hash) { if (StringUtils.isNotBlank(hash)) { List<User> list = getJdbcTemplate().query( - "SELECT logins.user_id, users.nick, users.banned FROM logins " + + "SELECT logins.user_id, users.nick, users.banned, users.lang FROM logins " + "INNER JOIN users ON logins.user_id = users.id WHERE logins.hash = ?", new UserMapper(), hash); @@ -651,4 +652,27 @@ public class UserServiceImpl extends BaseJdbcService implements UserService { user.getUid()); return list.isEmpty() ? "" : list.get(0) + "@mail.juick.com"; } + + @Transactional + @Override + public int deleteLoginForUser(final String name) { + if (StringUtils.isBlank(name)) + return 0; + + return getJdbcTemplate().update( + "delete from logins where user_id in (select id from users where nick = ?)", name); + } + + @Transactional + @Override + public int setLoginForUser(final int uid, final String loginHash) { + if (StringUtils.isEmpty(loginHash)) + return 0; + + return getNamedParameterJdbcTemplate().update( + "INSERT INTO logins (user_id, hash) VALUES(:uid, :hash) ON DUPLICATE KEY UPDATE hash = :hash", + new MapSqlParameterSource() + .addValue("hash", loginHash) + .addValue("uid", uid)); + } } diff --git a/juick-server/src/main/java/com/juick/service/security/JuickUserDetailsService.java b/juick-server/src/main/java/com/juick/service/security/JuickUserDetailsService.java new file mode 100644 index 00000000..d1fd9345 --- /dev/null +++ b/juick-server/src/main/java/com/juick/service/security/JuickUserDetailsService.java @@ -0,0 +1,34 @@ +package com.juick.service.security; + +import com.juick.server.security.entities.JuickUser; +import com.juick.service.UserService; +import org.apache.commons.lang3.StringUtils; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.util.Assert; + +/** + * Created by aalexeev on 11/28/16. + */ +public class JuickUserDetailsService implements UserDetailsService { + private final UserService userService; + + public JuickUserDetailsService(final UserService userService) { + Assert.notNull(userService); + this.userService = userService; + } + + @Override + public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException { + if (StringUtils.isBlank(username)) + throw new UsernameNotFoundException("Invalid user name " + username); + + com.juick.User user = userService.getFullyUserByName(username); + + if (user != null) + return new JuickUser(user); + + throw new UsernameNotFoundException("The username " + username + " is not found"); + } +} diff --git a/juick-server/src/main/java/com/juick/service/security/SimpleRememberMeServices.java b/juick-server/src/main/java/com/juick/service/security/SimpleRememberMeServices.java new file mode 100644 index 00000000..d5d54005 --- /dev/null +++ b/juick-server/src/main/java/com/juick/service/security/SimpleRememberMeServices.java @@ -0,0 +1,89 @@ +package com.juick.service.security; + +import com.juick.User; +import com.juick.server.security.entities.JuickUser; +import com.juick.service.UserService; +import com.juick.util.UserUtils; +import org.apache.commons.lang3.StringUtils; +import org.springframework.core.env.Environment; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.security.web.authentication.RememberMeServices; +import org.springframework.security.web.authentication.rememberme.AbstractRememberMeServices; +import org.springframework.security.web.authentication.rememberme.InvalidCookieException; +import org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationException; +import org.springframework.util.Assert; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.util.Optional; + +/** + * Created by aalexeev on 11/28/16. + */ +public class SimpleRememberMeServices extends AbstractRememberMeServices implements RememberMeServices { + private final UserService userService; + + public SimpleRememberMeServices( + final String key, final UserDetailsService userDetailsService, final UserService userService, final Environment environment) { + super(key, userDetailsService); + + Assert.notNull(userService); + Assert.notNull(environment); + + this.userService = userService; + + setCookieName(environment.getProperty("auth_cookie_name", "hash")); + setCookieDomain(environment.getProperty("web_domain", "juick.com")); + } + + @Override + public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) { + super.logout(request, response, authentication); + userService.deleteLoginForUser(authentication.getName()); + } + + @Override + protected void onLoginSuccess( + HttpServletRequest request, HttpServletResponse response, Authentication successfulAuthentication) { + String username = successfulAuthentication.getName(); + + logger.debug("Creating new persistent login for user " + username); + + try { + int uid = userService.getUIDbyName(username); + + Assert.isTrue(uid > 0); + + String hash = UserUtils.generateHash(16); + + userService.setLoginForUser(uid, hash); + + setCookie(new String[]{hash}, getTokenValiditySeconds(), request, response); + } catch (Exception e) { + logger.error("Failed to save cookies ", e); + } + } + + @Override + protected UserDetails processAutoLoginCookie( + String[] cookieTokens, HttpServletRequest request, HttpServletResponse response) + throws RememberMeAuthenticationException, UsernameNotFoundException { + String hash = cookieTokens[0]; + + if (StringUtils.isBlank(hash)) + throw new InvalidCookieException("Cookie is invalid, cookies " + cookieTokens); + + int uid = userService.getUIDbyHash(cookieTokens[0]); + if (uid <= 0) + throw new UsernameNotFoundException("User not found bash hash, cookies" + cookieTokens); + + Optional<User> userOptional = userService.getUserByUID(uid); + + Assert.isTrue(userOptional.isPresent()); + + return new JuickUser(userOptional.get()); + } +} diff --git a/juick-server/src/main/resources/juick.conf.example b/juick-server/src/main/resources/juick.conf.example index c91a42d2..e8ebf5d3 100644 --- a/juick-server/src/main/resources/juick.conf.example +++ b/juick-server/src/main/resources/juick.conf.example @@ -32,6 +32,9 @@ web_domain=juick.com # Authority cookie name (default value - "hash") auth_cookie_name=hash +# Authority remember-me key +auth_remember_me_key=3vHcy3OUDQlkpRDm + ### Template Settings (web page templates) # Show sponsors block diff --git a/juick-spring-www/src/main/java/com/juick/www/configuration/WebSecurityConfig.java b/juick-spring-www/src/main/java/com/juick/www/configuration/WebSecurityConfig.java index 3753a4aa..95a94642 100644 --- a/juick-spring-www/src/main/java/com/juick/www/configuration/WebSecurityConfig.java +++ b/juick-spring-www/src/main/java/com/juick/www/configuration/WebSecurityConfig.java @@ -1,8 +1,7 @@ package com.juick.www.configuration; import com.juick.service.UserService; -import com.juick.server.security.entities.JuickUser; -import org.apache.commons.lang3.StringUtils; +import com.juick.service.security.JuickUserDetailsService; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; @@ -10,7 +9,6 @@ import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.UserDetailsService; -import org.springframework.security.core.userdetails.UsernameNotFoundException; import javax.annotation.Resource; @@ -32,17 +30,7 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Bean("userDetailsService") @Override public UserDetailsService userDetailsServiceBean() throws Exception { - return username -> { - if (StringUtils.isBlank(username)) - throw new UsernameNotFoundException("Invalid user name " + username); - - com.juick.User user = userService.getUserByName(username); - - if (user != null) - return new JuickUser(user); - - throw new UsernameNotFoundException("The username " + username + " is not found"); - }; + return new JuickUserDetailsService(userService); } @Override |