Java Web series: Spring Security Basics, springsecurity

Source: Internet
Author: User

Java Web series: Spring Security Basics, springsecurity

Although Spring Security is much more advanced than JAAS, it is still inherently inadequate and cannot achieve authentication and authorization in ASP. NET. Here we will demonstrate the common functions of logging on, logging off, and remembering me. the user-defined providers for authentication avoid dependency on the database, and the authorized user-defined providers eliminate the negative side effects of role changes caused by loading role information from the cache.

1. Basic Spring Security Configuration Based on java config

(1) integrate with Spring MVC using AbstractSecurityWebApplicationInitializer

1 public class SecurityInitializer extends AbstractSecurityWebApplicationInitializer {2 }

(2) Use the Anonymous class to customize AuthenticationProvider, UserDetailsService, and SecurityContextRepository in websecurityjavaseradapter.

 1 @EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true) 2 @EnableWebSecurity 3 public class SecurityConfig extends WebSecurityConfigurerAdapter { 4  5     @Override 6     protected void configure(HttpSecurity http) throws Exception { 7         http.authorizeRequests().antMatchers("/account**", "/admin**").authenticated(); 8         http.formLogin().usernameParameter("userName").passwordParameter("password").loginPage("/login") 9                 .loginProcessingUrl("/login").successHandler(new SavedRequestAwareAuthenticationSuccessHandler()).and()10                 .logout().logoutUrl("/logout").logoutSuccessUrl("/");11         http.rememberMe().rememberMeParameter("rememberMe");12         http.csrf().disable();13         http.setSharedObject(SecurityContextRepository.class, new SecurityContextRepository() {14 15             private HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository();16 17             @Override18             public SecurityContext loadContext(HttpRequestResponseHolder requestResponseHolder) {19                 SecurityContext context = this.repo.loadContext(requestResponseHolder);20                 if (context != null && context.getAuthentication() != null) {21                     Membership membership = new Membership();22                     String username = context.getAuthentication().getPrincipal().toString();23                     String[] roles = membership.getRoles(username);24                     context.getAuthentication().getAuthorities();25                     UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username,26                             "password", convertStringArrayToAuthorities(roles));27                     context.setAuthentication(token);28                     System.out.println("check user role");29                 }30                 return context;31             }32 33             @Override34             public void saveContext(SecurityContext context, HttpServletRequest request, HttpServletResponse response) {35                 this.repo.saveContext(context, request, response);36             }37 38             @Override39             public boolean containsContext(HttpServletRequest request) {40                 return this.repo.containsContext(request);41             }42         });43     }44 45     @Autowired46     @Override47     protected void configure(AuthenticationManagerBuilder auth) throws Exception {48         auth.authenticationProvider(new AuthenticationProvider() {49 50             @Override51             public Authentication authenticate(Authentication authentication) throws AuthenticationException {52                 Membership membership = new Membership();53                 String username = authentication.getName();54                 String password = authentication.getCredentials().toString();55                 if (membership.validateUser(username, password)) {56                     String[] roles = membership.getRoles(username);57                     UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username,58                             "password", convertStringArrayToAuthorities(roles));59                     return token;60                 }61                 return null;62             }63 64             @Override65             public boolean supports(Class<?> authentication) {66                 return authentication.equals(UsernamePasswordAuthenticationToken.class);67             }68 69         });70         auth.userDetailsService(new UserDetailsService() {71 72             @Override73             public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {74                 Membership membership = new Membership();75                 if (membership.hasUser(username)) {76                     UserDetails user = new User(username, "password",77                             convertStringArrayToAuthorities(membership.getRoles(username)));78                     return user;79                 }80                 return null;81             }82         });83     }84 85     public Collection<? extends GrantedAuthority> convertStringArrayToAuthorities(String[] roles) {86         List<SimpleGrantedAuthority> list = new ArrayList<SimpleGrantedAuthority>();87         for (String role : roles) {88             list.add(new SimpleGrantedAuthority(role));89         }90         return list;91     }92 }
2. Use @ PreAuthorize to control permissions at the Controller level

(1) Use the @ PreAuthorize ("isAuthenticated ()") annotation to verify Logon

1     @PreAuthorize("isAuthenticated()")2     @ResponseBody3     @RequestMapping(value = "/account")4     public String account() {5         return "account";6     }

(2) Use the @ PreAuthorize ("hasAuthority ('admin')") annotation to verify the role

1     @PreAuthorize("hasAuthority('admin')")2     @ResponseBody3     @RequestMapping("/admin")4     public String admin() {5         return "admin";6     }
3. logon and logout

You can use the built-in function to log out and customize the controller and view.

1     @RequestMapping(value = "/login")2     public String login(@RequestParam(value = "error", required = false) String error,3             @ModelAttribute("model") UserModel model, BindingResult result) {4         if (error != null) {5             result.rejectValue("userName", "", "Invalid username and password!");6         }7         return "login";8     }

View:

 1 <%@ page language="java" pageEncoding="UTF-8"%> 2 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> 3 <%@ taglib uri="http://www.springframework.org/tags" prefix="s"%> 4 <%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%> 5 <!DOCTYPE HTML> 6 4. Spring Security core object

Authentication and authorization of the core ASP. NET must be an HttpModule, and Java is a Filter. There is nothing to say about it. Up to now, two sets of combinations (HttpApplicaiton + HttpModule + HttpHandler) (ServletContext + Filter + Servlet) the core concept is already proficient.

(1) security context SecurityContext

In ASP. NET, we can use HttpContext. User to obtain the IPrincipal instance, which is implemented through the HttpModuel (FormsAuthenticationModule) mechanism. In Spring Security, SecurityContext is obtained through the corresponding Filter (SecurityContextPersistenceFilter) mechanism. SecurityContextPersistenceFilter delegates the function to the SecurityContextRepository instance for implementation. Therefore, we have customized the SecurityContextRepository implementation above to refresh the role information.

(2) AuthenticationProvider

Authenticate Method of the AuthenticationProvider object and return the Authentication object. The Authentication object is a sub-interface of the Java Principal interface. The user-defined AuthenticationProvider simply uses the username as the parameter of the Authentication implementation class UsernamePasswordAuthenticationToken. If necessary, other objects can be passed through SecurityContextHolder. getContext (). getAuthentication (). getPrincipal.

(3) User information provider UserDetailsService

UserDetailsService is required only when AuthenticationProvider is used for verification. UserDetailsService returns a UserDetails object. In AuthenticationProvider, call UserDetailsService to pass the UserDetails object to the Authentication object as the Principal parameter. In this way, we can obtain the UserDetails object through the following statement in the Controller. In fact, it is most practical to pass the user name as the Principal parameter. It is better to create a custom UserDetails to return information from the Service using the user name in the Custom POJO. Even if you use the UserDetails object, you do not have to use UserDetailsService. You can directly construct and pass the UserDetails object in AuthenticationProvider. The UserDetailsService of the code above is only used as a demonstration and will not be called in fact.

1 UserDetails userDetails =2  (UserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
Reference

(1) http://docs.spring.io/autorepo/docs/spring-security/3.2.x/guides/hellomvc.html

(2) http://docs.spring.io/spring-security/site/docs/4.0.4.CI-SNAPSHOT/reference/htmlsingle/

(3) http://docs.spring.io/spring/docs/current/spring-framework-reference/html/view.html

JAAS does not focus on the core data structure and defines a bunch of process dependencies that are not as good as they are. Although Spring Security improves usability, It inherits an unrealistic fantasy style from JAAS. It is enough to provide the core data structure and interface, from password encryption to user information retrieval to dependency on Cache and database. Spring Object-based dependency injection is no longer applicable, spring Security deviated from its core. The built-in logic is unreasonable, and the external logic is difficult to use. The word "integration" is the combination of a bunch of frameworks. When the type-based dependency injection framework can replace Spring and the data structure-based verification framework can replace Spring Security, and the productivity of Java Web development is estimated to increase. Up to now, I have not found an annotation-based front-end unified verification framework. Without such a framework, it is a disaster to quickly create a demo model. In any case, SSH should at least have an overall grasp of its basic configuration and core objects, at least you must be able to quickly locate problems encountered during development and respond to most technical problems based on the source code.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.