代碼下載地址 java
git@github.com:only-care/springboot-security.gitgit
1、權限驗證攔截器,重寫attemptAuthentication實現自定義攔截直接執行校驗權限處理,封裝爲UsernamePasswordAuthenticationToken返回認證github
import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.security.authentication.AuthenticationServiceException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; public class OpenIdAuthenticationFilter extends UsernamePasswordAuthenticationFilter { //僅處理post private boolean postOnly = true; /*** * 用於攔截封裝token具體驗證交由anthenticationManager屬性完成,能夠在建立時本身設置 */ @Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException { if (postOnly && !request.getMethod().equals("POST")) { throw new AuthenticationServiceException( "Authentication method not supported: " + request.getMethod()); } String username = request.getParameter("username"); //默認 String password = request.getParameter("password"); username = username == null?"":username.trim(); password = password == null?"":password; UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken( username, password); authRequest.setDetails(request);//放入token 的detials中 //默認認證成功 final List<GrantedAuthority> AUTHORITIES = new ArrayList<GrantedAuthority>(); AUTHORITIES.add(new SimpleGrantedAuthority("ROLE_USER")); return new UsernamePasswordAuthenticationToken(authRequest.getPrincipal(), authRequest.getCredentials(), AUTHORITIES); } }
2、將自定義的filter添加到httpSecurity配置完成,結果以下web
@RestController @EnableWebSecurity @SpringBootApplication public class StartApp extends WebSecurityConfigurerAdapter{ @RequestMapping("/") String index() { return "Hello World!"; } public static void main(String[] args) { SpringApplication.run(StartApp.class, args); } @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests().anyRequest().authenticated().and().formLogin().and().httpBasic(); //添加自定義攔截器到httpSecurity OpenIdAuthenticationFilter openIdAuthenticationFilter = new OpenIdAuthenticationFilter(); //此處能夠添加認證處理對象 openIdAuthenticationFilter.setAuthenticationManager(null); openIdAuthenticationFilter.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher("/login", "POST")); http.addFilter(openIdAuthenticationFilter); } }