瀏覽代碼

新增i健康分支

chenweida 7 年之前
父節點
當前提交
f04c161c56
共有 17 個文件被更改,包括 1111 次插入1119 次删除
  1. 4 4
      app/app-iot-server/pom.xml
  2. 11 11
      app/app-iot-server/src/main/java/com/yihu/ehr/iot/controller/common/LoginController.java
  3. 19 19
      app/app-iot-server/src/main/java/com/yihu/ehr/iot/security/config/EhrWebHttpSessionConfiguration.java
  4. 135 131
      app/app-iot-server/src/main/java/com/yihu/ehr/iot/security/config/EhrWebSecurityConfiguration.java
  5. 95 95
      app/app-iot-server/src/main/java/com/yihu/ehr/iot/security/core/EhrWebAccessDecisionManager.java
  6. 40 40
      app/app-iot-server/src/main/java/com/yihu/ehr/iot/security/core/EhrWebAuthenticationFailureHandler.java
  7. 156 156
      app/app-iot-server/src/main/java/com/yihu/ehr/iot/security/core/EhrWebAuthenticationProvider.java
  8. 65 65
      app/app-iot-server/src/main/java/com/yihu/ehr/iot/security/core/EhrWebAuthenticationSuccessHandler.java
  9. 54 54
      app/app-iot-server/src/main/java/com/yihu/ehr/iot/security/core/EhrWebAuthenticationToken.java
  10. 55 55
      app/app-iot-server/src/main/java/com/yihu/ehr/iot/security/core/EhrWebContextLogoutHandler.java
  11. 47 47
      app/app-iot-server/src/main/java/com/yihu/ehr/iot/security/core/EhrWebUserDetails.java
  12. 85 87
      app/app-iot-server/src/main/java/com/yihu/ehr/iot/security/core/EhrWebUserDetailsService.java
  13. 177 177
      app/app-iot-server/src/main/java/com/yihu/ehr/iot/security/core/EhrWebUsernamePasswordAuthenticationFilter.java
  14. 36 36
      app/app-iot-server/src/main/java/com/yihu/ehr/iot/security/entryPoint/LoginEntryPoint.java
  15. 20 22
      app/app-iot-server/src/main/java/com/yihu/ehr/iot/service/common/BaseService.java
  16. 64 72
      app/app-iot-server/src/main/java/com/yihu/ehr/iot/service/common/LoginService.java
  17. 48 48
      app/app-iot-server/src/main/java/com/yihu/ehr/iot/util/CurrentRequest.java

+ 4 - 4
app/app-iot-server/pom.xml

@ -100,10 +100,10 @@
            <version>4.0.0.RELEASE</version>
        </dependency>-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <!--<dependency>-->
            <!--<groupId>org.springframework.boot</groupId>-->
            <!--<artifactId>spring-boot-starter-security</artifactId>-->
        <!--</dependency>-->
        <dependency>
            <groupId>org.apache.tiles</groupId>

+ 11 - 11
app/app-iot-server/src/main/java/com/yihu/ehr/iot/controller/common/LoginController.java

@ -55,7 +55,7 @@ public class LoginController extends BaseController{
            @RequestParam(value = "userName") String userName,
            @ApiParam(name = "password", value = "密码")
            @RequestParam(value = "password") String password) {
            return loginService.login(request, userName, password);
            return loginService.loginyanshi(request, userName, password);
    }
    /**
@ -89,14 +89,14 @@ public class LoginController extends BaseController{
        response.sendRedirect(contextPath + "/front/views/signin.html?clientId=" + clientId);
    }
    /*
     * 自动登录
     */
    @RequestMapping(value = "/autoLogin", method = RequestMethod.POST)
    @ResponseBody
    public Envelop autoLogin(HttpServletRequest request, Model model,
                             @ApiParam(name = "token", value = "TOKEN")
                             @RequestParam(value = "token") String token) throws Exception {
        return loginService.autoLogin(request, model, token);
    }
//    /*
//     * 自动登录
//     */
//    @RequestMapping(value = "/autoLogin", method = RequestMethod.POST)
//    @ResponseBody
//    public Envelop autoLogin(HttpServletRequest request, Model model,
//                             @ApiParam(name = "token", value = "TOKEN")
//                             @RequestParam(value = "token") String token) throws Exception {
//        return loginService.autoLogin(request, model, token);
//    }
}

+ 19 - 19
app/app-iot-server/src/main/java/com/yihu/ehr/iot/security/config/EhrWebHttpSessionConfiguration.java

@ -1,19 +1,19 @@
package com.yihu.ehr.iot.security.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.core.session.SessionRegistryImpl;
/**
 * Created by progr1mmer on 2018/1/27.
 */
@Configuration
//@EnableRedisHttpSession
public class EhrWebHttpSessionConfiguration {
    @Bean
    SessionRegistry sessionRegistry(){
        return new SessionRegistryImpl();
    }
}
//package com.yihu.ehr.iot.security.config;
//
//import org.springframework.context.annotation.Bean;
//import org.springframework.context.annotation.Configuration;
//import org.springframework.security.core.session.SessionRegistry;
//import org.springframework.security.core.session.SessionRegistryImpl;
//
///**
// * Created by progr1mmer on 2018/1/27.
// */
//@Configuration
////@EnableRedisHttpSession
//public class EhrWebHttpSessionConfiguration {
//
//    @Bean
//    SessionRegistry sessionRegistry(){
//        return new SessionRegistryImpl();
//    }
//}

+ 135 - 131
app/app-iot-server/src/main/java/com/yihu/ehr/iot/security/config/EhrWebSecurityConfiguration.java

@ -1,131 +1,135 @@
package com.yihu.ehr.iot.security.config;
import com.yihu.ehr.iot.security.core.*;
import com.yihu.ehr.iot.security.entryPoint.LoginEntryPoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
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.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.session.ConcurrentSessionControlAuthenticationStrategy;
/**
 * Created by progr1mmer on 2018/1/26.
 */
@Configuration
@EnableWebSecurity
public class EhrWebSecurityConfiguration extends WebSecurityConfigurerAdapter {
    @Value("${app.oauth2InnerUrl}")
    protected String oauth2InnerUrl;
    @Value("${service-gateway.profileInnerUrl}")
    protected String profileInnerUrl;
    @Autowired
    private EhrWebAuthenticationProvider ehrWebAuthenticationProvider;
    @Autowired
    private EhrWebAuthenticationSuccessHandler ehrWebAuthenticationSuccessHandler;
    @Autowired
    private EhrWebAuthenticationFailureHandler ehrWebAuthenticationFailureHandler;
    //@Autowired
    //private EhrWebAccessDecisionManager ehrWebAccessDecisionManager;
    @Autowired
    private SessionRegistry sessionRegistry;
    @Autowired
    private LoginEntryPoint loginEntryPoint;
    @Autowired
    private EhrWebContextLogoutHandler ehrWebContextLogoutHandler;
    @Override
    public void configure(WebSecurity web) throws Exception {
        //web.ignoring().antMatchers("/ambulance/search"); //忽略授权地址
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // ---------- 自定义Filter Start ----------
        EhrWebUsernamePasswordAuthenticationFilter ehrWebUsernamePasswordAuthenticationFilter = new EhrWebUsernamePasswordAuthenticationFilter(oauth2InnerUrl, profileInnerUrl);
        ehrWebUsernamePasswordAuthenticationFilter.setAuthenticationSuccessHandler(ehrWebAuthenticationSuccessHandler);
        ehrWebUsernamePasswordAuthenticationFilter.setAuthenticationFailureHandler(ehrWebAuthenticationFailureHandler);
        ehrWebUsernamePasswordAuthenticationFilter.setAuthenticationManager(authenticationManagerBean());
        ehrWebUsernamePasswordAuthenticationFilter.setSessionAuthenticationStrategy(new ConcurrentSessionControlAuthenticationStrategy(sessionRegistry));
        http.addFilterBefore(ehrWebUsernamePasswordAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
        // ---------- 自定义Filter End ----------
        //http.sessionManagement().maximumSessions(3).expiredUrl("/login?expired").sessionRegistry(sessionRegistry);
        //http.addFilter(ehrWebUsernamePasswordAuthenticationFilter);
        http.authorizeRequests()
                //.accessDecisionManager(ehrWebAccessDecisionManager)
                //.antMatchers("/front/views/*.html").hasRole("USER") //拦截html
                //.antMatchers("/user").hasRole("USER")
                //.antMatchers("/ambulance/**").hasRole("USER")
                //.antMatchers("/admin/**").hasRole("ADMIN")
                .antMatchers("/front/css/**").permitAll()
                .antMatchers("/front/fonts/**").permitAll()
                .antMatchers("/front/images/**").permitAll()
                .antMatchers("/front/js/**").permitAll()
                .antMatchers("/front/views/signin.html").permitAll()
                .antMatchers("/login/**").permitAll()
                .antMatchers("/svr-iot/wlyy/**").permitAll()//健康监测平台没有做登录(这里添加免登录验证)
                .antMatchers("/svr-iot/fileUpload/commonUpload").permitAll()//公共的文件上传(这里添加免登录验证)
                .antMatchers("/front/views/**").hasRole("USER")
                .antMatchers("/**").hasRole("USER")
                .and().formLogin().loginPage("/login")
                .and().exceptionHandling().authenticationEntryPoint(loginEntryPoint)
                .and().logout().addLogoutHandler(ehrWebContextLogoutHandler).logoutUrl("/logout").logoutSuccessUrl("/login")
                .and().headers().frameOptions().disable()
                .and().csrf().disable();
    }
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(ehrWebAuthenticationProvider); //自定义认证提供者
    }
    @Bean
    EhrWebUserDetailsService ehrWebUserDetailsService(){
        return new EhrWebUserDetailsService(profileInnerUrl);
    }
    @Bean
    EhrWebAuthenticationProvider ehrWebAuthenticationProvider(UserDetailsService userDetailsService) {
        EhrWebAuthenticationProvider ehrWebAuthenticationProvider = new EhrWebAuthenticationProvider(userDetailsService);
        ehrWebAuthenticationProvider.setPasswordEncoder(new Md5PasswordEncoder());
        return ehrWebAuthenticationProvider;
    }
    @Bean
    EhrWebAuthenticationSuccessHandler ehrWebAuthenticationSuccessHandler(){
        return new EhrWebAuthenticationSuccessHandler();
    }
    @Bean
    EhrWebAuthenticationFailureHandler ehrWebAuthenticationFailureHandler(){
        return new EhrWebAuthenticationFailureHandler();
    }
    @Bean
    EhrWebContextLogoutHandler ehrWebContextLogoutHandler(){
        return new EhrWebContextLogoutHandler();
    }
    @Bean
    LoginEntryPoint loginEntryPoint(){
        return new LoginEntryPoint("/login");
    }
    /**
    @Bean
    EhrWebAccessDecisionManager ehrWebAccessDecisionManager() {
        return new EhrWebAccessDecisionManager(null);
    }
    */
}
//package com.yihu.ehr.iot.security.config;
//
//import com.yihu.ehr.iot.security.core.*;
//import com.yihu.ehr.iot.security.entryPoint.LoginEntryPoint;
//import com.yihu.ehr.iot.service.common.LoginService;
//import com.yihu.ehr.iot.yanshi.dao.UserDao;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.context.annotation.Bean;
//import org.springframework.context.annotation.Configuration;
//import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
//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.builders.WebSecurity;
//import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
//import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
//import org.springframework.security.core.session.SessionRegistry;
//import org.springframework.security.core.userdetails.UserDetailsService;
//import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
//import org.springframework.security.web.authentication.session.ConcurrentSessionControlAuthenticationStrategy;
//
///**
// * Created by progr1mmer on 2018/1/26.
// */
//@Configuration
//@EnableWebSecurity
//public class EhrWebSecurityConfiguration extends WebSecurityConfigurerAdapter {
//
//    @Value("${app.oauth2InnerUrl}")
//    protected String oauth2InnerUrl;
//    @Value("${service-gateway.profileInnerUrl}")
//    protected String profileInnerUrl;
//
//    @Autowired
//    private EhrWebAuthenticationProvider ehrWebAuthenticationProvider;
//    @Autowired
//    private EhrWebAuthenticationSuccessHandler ehrWebAuthenticationSuccessHandler;
//    @Autowired
//    private EhrWebAuthenticationFailureHandler ehrWebAuthenticationFailureHandler;
//    //@Autowired
//    //private EhrWebAccessDecisionManager ehrWebAccessDecisionManager;
//    @Autowired
//    private SessionRegistry sessionRegistry;
//    @Autowired
//    private LoginEntryPoint loginEntryPoint;
//    @Autowired
//    private EhrWebContextLogoutHandler ehrWebContextLogoutHandler;
//
//    @Override
//    public void configure(WebSecurity web) throws Exception {
//        //web.ignoring().antMatchers("/ambulance/search"); //忽略授权地址
//    }
//
//    @Override
//    protected void configure(HttpSecurity http) throws Exception {
//        // ---------- 自定义Filter Start ----------
//        EhrWebUsernamePasswordAuthenticationFilter ehrWebUsernamePasswordAuthenticationFilter = new EhrWebUsernamePasswordAuthenticationFilter(oauth2InnerUrl, profileInnerUrl);
//        ehrWebUsernamePasswordAuthenticationFilter.setAuthenticationSuccessHandler(ehrWebAuthenticationSuccessHandler);
//        ehrWebUsernamePasswordAuthenticationFilter.setAuthenticationFailureHandler(ehrWebAuthenticationFailureHandler);
//        ehrWebUsernamePasswordAuthenticationFilter.setAuthenticationManager(authenticationManagerBean());
//        ehrWebUsernamePasswordAuthenticationFilter.setSessionAuthenticationStrategy(new ConcurrentSessionControlAuthenticationStrategy(sessionRegistry));
//        http.addFilterBefore(ehrWebUsernamePasswordAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
//        // ---------- 自定义Filter End ----------
//        //http.sessionManagement().maximumSessions(3).expiredUrl("/login?expired").sessionRegistry(sessionRegistry);
//        //http.addFilter(ehrWebUsernamePasswordAuthenticationFilter);
//        http.authorizeRequests()
//                //.accessDecisionManager(ehrWebAccessDecisionManager)
//                //.antMatchers("/front/views/*.html").hasRole("USER") //拦截html
//                //.antMatchers("/user").hasRole("USER")
//                //.antMatchers("/ambulance/**").hasRole("USER")
//                //.antMatchers("/admin/**").hasRole("ADMIN")
//                .antMatchers("/front/css/**").permitAll()
//                .antMatchers("/front/fonts/**").permitAll()
//                .antMatchers("/front/images/**").permitAll()
//                .antMatchers("/front/js/**").permitAll()
//                .antMatchers("/front/views/signin.html").permitAll()
//                .antMatchers("/login/**").permitAll()
//                .antMatchers("/svr-iot/wlyy/**").permitAll()//健康监测平台没有做登录(这里添加免登录验证)
//                .antMatchers("/svr-iot/fileUpload/commonUpload").permitAll()//公共的文件上传(这里添加免登录验证)
//                .antMatchers("/front/views/**").hasRole("USER")
//                .antMatchers("/**").hasRole("USER")
//                .and().formLogin().loginPage("/login")
//                .and().exceptionHandling().authenticationEntryPoint(loginEntryPoint)
//                .and().logout().addLogoutHandler(ehrWebContextLogoutHandler).logoutUrl("/logout").logoutSuccessUrl("/login")
//                .and().headers().frameOptions().disable()
//                .and().csrf().disable();
//    }
//
//    @Override
//    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//        auth.authenticationProvider(ehrWebAuthenticationProvider); //自定义认证提供者
//    }
//
//    @Autowired
//    private UserDao userDao;
//    @Bean
//    EhrWebUserDetailsService ehrWebUserDetailsService(){
//        return new EhrWebUserDetailsService(profileInnerUrl,userDao);
//    }
//
//    @Bean
//    EhrWebAuthenticationProvider ehrWebAuthenticationProvider(UserDetailsService userDetailsService) {
//        EhrWebAuthenticationProvider ehrWebAuthenticationProvider = new EhrWebAuthenticationProvider(userDetailsService);
//        ehrWebAuthenticationProvider.setPasswordEncoder(new Md5PasswordEncoder());
//        return ehrWebAuthenticationProvider;
//    }
//
//    @Bean
//    EhrWebAuthenticationSuccessHandler ehrWebAuthenticationSuccessHandler(){
//        return new EhrWebAuthenticationSuccessHandler();
//    }
//
//    @Bean
//    EhrWebAuthenticationFailureHandler ehrWebAuthenticationFailureHandler(){
//        return new EhrWebAuthenticationFailureHandler();
//    }
//
//    @Bean
//    EhrWebContextLogoutHandler ehrWebContextLogoutHandler(){
//        return new EhrWebContextLogoutHandler();
//    }
//
//    @Bean
//    LoginEntryPoint loginEntryPoint(){
//        return new LoginEntryPoint("/login");
//    }
//
//    /**
//    @Bean
//    EhrWebAccessDecisionManager ehrWebAccessDecisionManager() {
//        return new EhrWebAccessDecisionManager(null);
//    }
//    */
//
//}

+ 95 - 95
app/app-iot-server/src/main/java/com/yihu/ehr/iot/security/core/EhrWebAccessDecisionManager.java

@ -1,95 +1,95 @@
package com.yihu.ehr.iot.security.core;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.MessageSource;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDecisionVoter;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.vote.AbstractAccessDecisionManager;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.SpringSecurityMessageSource;
import org.springframework.util.Assert;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
/**
 * Final AccessDecisionManager
 * Created by progr1mmer on 2018/1/26.
 */
public class EhrWebAccessDecisionManager extends AbstractAccessDecisionManager {
    private final Log logger = LogFactory.getLog(this.getClass());
    private List<AccessDecisionVoter<? extends Object>> decisionVoters;
    protected MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();
    private boolean allowIfAllAbstainDecisions = false;
    public EhrWebAccessDecisionManager(List<AccessDecisionVoter<? extends Object>> decisionVoters) {
        super(decisionVoters);
        Assert.notEmpty(decisionVoters, "A list of AccessDecisionVoters is required");
        this.decisionVoters = decisionVoters;
    }
    @Override
    public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> collection) throws AccessDeniedException, InsufficientAuthenticationException {
    }
    public void afterPropertiesSet() throws Exception {
        Assert.notEmpty(this.decisionVoters, "A list of AccessDecisionVoters is required");
        Assert.notNull(this.messages, "A message source must be set");
    }
    public List<AccessDecisionVoter<? extends Object>> getDecisionVoters() {
        return this.decisionVoters;
    }
    public boolean isAllowIfAllAbstainDecisions() {
        return this.allowIfAllAbstainDecisions;
    }
    public void setAllowIfAllAbstainDecisions(boolean allowIfAllAbstainDecisions) {
        this.allowIfAllAbstainDecisions = allowIfAllAbstainDecisions;
    }
    public void setMessageSource(MessageSource messageSource) {
        this.messages = new MessageSourceAccessor(messageSource);
    }
    public boolean supports(ConfigAttribute attribute) {
        Iterator var2 = this.decisionVoters.iterator();
        AccessDecisionVoter voter;
        do {
            if(!var2.hasNext()) {
                return false;
            }
            voter = (AccessDecisionVoter)var2.next();
        } while(!voter.supports(attribute));
        return true;
    }
    public boolean supports(Class<?> clazz) {
        Iterator var2 = this.decisionVoters.iterator();
        AccessDecisionVoter voter;
        do {
            if(!var2.hasNext()) {
                return true;
            }
            voter = (AccessDecisionVoter)var2.next();
        } while(voter.supports(clazz));
        return false;
    }
}
//package com.yihu.ehr.iot.security.core;
//
//import org.apache.commons.logging.Log;
//import org.apache.commons.logging.LogFactory;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.context.MessageSource;
//import org.springframework.context.support.MessageSourceAccessor;
//import org.springframework.security.access.AccessDecisionManager;
//import org.springframework.security.access.AccessDecisionVoter;
//import org.springframework.security.access.AccessDeniedException;
//import org.springframework.security.access.ConfigAttribute;
//import org.springframework.security.access.vote.AbstractAccessDecisionManager;
//import org.springframework.security.authentication.InsufficientAuthenticationException;
//import org.springframework.security.core.Authentication;
//import org.springframework.security.core.SpringSecurityMessageSource;
//import org.springframework.util.Assert;
//
//import java.util.Collection;
//import java.util.Iterator;
//import java.util.List;
//
///**
// * Final AccessDecisionManager
// * Created by progr1mmer on 2018/1/26.
// */
//public class EhrWebAccessDecisionManager extends AbstractAccessDecisionManager {
//
//    private final Log logger = LogFactory.getLog(this.getClass());
//    private List<AccessDecisionVoter<? extends Object>> decisionVoters;
//    protected MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();
//    private boolean allowIfAllAbstainDecisions = false;
//
//    public EhrWebAccessDecisionManager(List<AccessDecisionVoter<? extends Object>> decisionVoters) {
//        super(decisionVoters);
//        Assert.notEmpty(decisionVoters, "A list of AccessDecisionVoters is required");
//        this.decisionVoters = decisionVoters;
//    }
//
//    @Override
//    public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> collection) throws AccessDeniedException, InsufficientAuthenticationException {
//
//    }
//
//    public void afterPropertiesSet() throws Exception {
//        Assert.notEmpty(this.decisionVoters, "A list of AccessDecisionVoters is required");
//        Assert.notNull(this.messages, "A message source must be set");
//    }
//
//    public List<AccessDecisionVoter<? extends Object>> getDecisionVoters() {
//        return this.decisionVoters;
//    }
//
//    public boolean isAllowIfAllAbstainDecisions() {
//        return this.allowIfAllAbstainDecisions;
//    }
//
//    public void setAllowIfAllAbstainDecisions(boolean allowIfAllAbstainDecisions) {
//        this.allowIfAllAbstainDecisions = allowIfAllAbstainDecisions;
//    }
//
//    public void setMessageSource(MessageSource messageSource) {
//        this.messages = new MessageSourceAccessor(messageSource);
//    }
//
//    public boolean supports(ConfigAttribute attribute) {
//        Iterator var2 = this.decisionVoters.iterator();
//
//        AccessDecisionVoter voter;
//        do {
//            if(!var2.hasNext()) {
//                return false;
//            }
//
//            voter = (AccessDecisionVoter)var2.next();
//        } while(!voter.supports(attribute));
//
//        return true;
//    }
//
//    public boolean supports(Class<?> clazz) {
//        Iterator var2 = this.decisionVoters.iterator();
//
//        AccessDecisionVoter voter;
//        do {
//            if(!var2.hasNext()) {
//                return true;
//            }
//
//            voter = (AccessDecisionVoter)var2.next();
//        } while(voter.supports(clazz));
//
//        return false;
//    }
//}

+ 40 - 40
app/app-iot-server/src/main/java/com/yihu/ehr/iot/security/core/EhrWebAuthenticationFailureHandler.java

@ -1,40 +1,40 @@
package com.yihu.ehr.iot.security.core;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.ehr.util.rest.Envelop;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
 * Created by progr1mmer on 2018/1/26.
 */
public class EhrWebAuthenticationFailureHandler implements AuthenticationFailureHandler {
    @Autowired
    private ObjectMapper objectMapper;
    /**
     * Step 4
     * @param httpServletRequest
     * @param httpServletResponse
     * @param authException
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException authException) throws IOException, ServletException {
        Envelop envelop = new Envelop();
        envelop.setSuccessFlg(false);
        envelop.setErrorMsg("invalid account or password !");
        envelop.setErrorCode(-1);
        httpServletResponse.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        httpServletResponse.getWriter().print(objectMapper.writeValueAsString(envelop));
    }
}
//package com.yihu.ehr.iot.security.core;
//
//import com.fasterxml.jackson.databind.ObjectMapper;
//import com.yihu.ehr.util.rest.Envelop;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.http.MediaType;
//import org.springframework.security.core.AuthenticationException;
//import org.springframework.security.web.authentication.AuthenticationFailureHandler;
//
//import javax.servlet.ServletException;
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
//import java.io.IOException;
//
///**
// * Created by progr1mmer on 2018/1/26.
// */
//public class EhrWebAuthenticationFailureHandler implements AuthenticationFailureHandler {
//
//    @Autowired
//    private ObjectMapper objectMapper;
//
//    /**
//     * Step 4
//     * @param httpServletRequest
//     * @param httpServletResponse
//     * @param authException
//     * @throws IOException
//     * @throws ServletException
//     */
//    @Override
//    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException authException) throws IOException, ServletException {
//        Envelop envelop = new Envelop();
//        envelop.setSuccessFlg(false);
//        envelop.setErrorMsg("invalid account or password !");
//        envelop.setErrorCode(-1);
//        httpServletResponse.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
//        httpServletResponse.getWriter().print(objectMapper.writeValueAsString(envelop));
//    }
//}

+ 156 - 156
app/app-iot-server/src/main/java/com/yihu/ehr/iot/security/core/EhrWebAuthenticationProvider.java

@ -1,156 +1,156 @@
package com.yihu.ehr.iot.security.core;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider;
import org.springframework.security.authentication.dao.SaltSource;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.security.authentication.encoding.PlaintextPasswordEncoder;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.session.SessionRegistry;
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;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
/**
 * Created by progr1mmer on 2018/1/26.
 */
public class EhrWebAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider {
    private static final String USER_NOT_FOUND_PASSWORD = "userNotFoundPassword";
    private PasswordEncoder passwordEncoder;
    private String userNotFoundEncodedPassword;
    private SaltSource saltSource;
    private UserDetailsService userDetailsService;
    private SessionRegistry sessionRegistry;
    public EhrWebAuthenticationProvider() {
        this.setPasswordEncoder((PasswordEncoder)(new PlaintextPasswordEncoder()));
    }
    public EhrWebAuthenticationProvider(UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
        this.setPasswordEncoder((PasswordEncoder)(new PlaintextPasswordEncoder()));
    }
    /**
    public EhrWebAuthenticationProvider(UserDetailsService userDetailsService, SessionRegistry sessionRegistry) {
        this.userDetailsService = userDetailsService;
        this.sessionRegistry = sessionRegistry;
        this.setPasswordEncoder((PasswordEncoder)(new PlaintextPasswordEncoder()));
    }
     */
    /**
     * Step 3
     * @param userDetails
     * @param authentication
     * @throws AuthenticationException
     */
    protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
        Object salt = null;
        if(this.saltSource != null) {
            salt = this.saltSource.getSalt(userDetails);
        }
        if(authentication.getCredentials() == null) {
            this.logger.debug("Authentication failed: no credentials provided");
            throw new BadCredentialsException(this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
        } else {
            EhrWebAuthenticationToken ehrWebAuthenticationToken = (EhrWebAuthenticationToken) authentication;
            if(!ehrWebAuthenticationToken.isSso()) {
                String presentedPassword = authentication.getCredentials().toString();
                if (!this.passwordEncoder.isPasswordValid(userDetails.getPassword(), presentedPassword, salt)) {
                    this.logger.debug("Authentication failed: password does not match stored value");
                    throw new BadCredentialsException(this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
                }
            }
            //HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            //sessionRegistry.registerNewSession(request.getSession().getId(), userDetails);
        }
    }
    protected void doAfterPropertiesSet() throws Exception {
        Assert.notNull(this.userDetailsService, "A UserDetailsService must be set");
    }
    protected final UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
        UserDetails loadedUser;
        try {
            loadedUser = this.getUserDetailsService().loadUserByUsername(username);
        } catch (UsernameNotFoundException var6) {
            if(authentication.getCredentials() != null) {
                String presentedPassword = authentication.getCredentials().toString();
                this.passwordEncoder.isPasswordValid(this.userNotFoundEncodedPassword, presentedPassword, (Object)null);
            }
            throw var6;
        } catch (Exception var7) {
            throw new InternalAuthenticationServiceException(var7.getMessage(), var7);
        }
        if(loadedUser == null) {
            throw new InternalAuthenticationServiceException("UserDetailsService returned null, which is an interface contract violation");
        } else {
            return loadedUser;
        }
    }
    public void setPasswordEncoder(Object passwordEncoder) {
        Assert.notNull(passwordEncoder, "passwordEncoder cannot be null");
        if(passwordEncoder instanceof PasswordEncoder) {
            this.setPasswordEncoder((PasswordEncoder)passwordEncoder);
        } else if(passwordEncoder instanceof org.springframework.security.crypto.password.PasswordEncoder) {
            final org.springframework.security.crypto.password.PasswordEncoder delegate = (org.springframework.security.crypto.password.PasswordEncoder)passwordEncoder;
            this.setPasswordEncoder(new PasswordEncoder() {
                public String encodePassword(String rawPass, Object salt) {
                    this.checkSalt(salt);
                    return delegate.encode(rawPass);
                }
                public boolean isPasswordValid(String encPass, String rawPass, Object salt) {
                    this.checkSalt(salt);
                    return delegate.matches(rawPass, encPass);
                }
                private void checkSalt(Object salt) {
                    Assert.isNull(salt, "Salt value must be null when used with crypto module PasswordEncoder");
                }
            });
        } else {
            throw new IllegalArgumentException("passwordEncoder must be a PasswordEncoder instance");
        }
    }
    private void setPasswordEncoder(PasswordEncoder passwordEncoder) {
        Assert.notNull(passwordEncoder, "passwordEncoder cannot be null");
        this.userNotFoundEncodedPassword = passwordEncoder.encodePassword("userNotFoundPassword", (Object)null);
        this.passwordEncoder = passwordEncoder;
    }
    protected PasswordEncoder getPasswordEncoder() {
        return this.passwordEncoder;
    }
    public void setSaltSource(SaltSource saltSource) {
        this.saltSource = saltSource;
    }
    protected SaltSource getSaltSource() {
        return this.saltSource;
    }
    public void setUserDetailsService(UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }
    protected UserDetailsService getUserDetailsService() {
        return this.userDetailsService;
    }
}
//package com.yihu.ehr.iot.security.core;
//
//import org.springframework.security.authentication.BadCredentialsException;
//import org.springframework.security.authentication.InternalAuthenticationServiceException;
//import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
//import org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider;
//import org.springframework.security.authentication.dao.SaltSource;
//import org.springframework.security.authentication.encoding.PasswordEncoder;
//import org.springframework.security.authentication.encoding.PlaintextPasswordEncoder;
//import org.springframework.security.core.AuthenticationException;
//import org.springframework.security.core.session.SessionRegistry;
//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;
//import org.springframework.web.context.request.RequestContextHolder;
//import org.springframework.web.context.request.ServletRequestAttributes;
//
//import javax.servlet.http.HttpServletRequest;
//
///**
// * Created by progr1mmer on 2018/1/26.
// */
//public class EhrWebAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider {
//
//    private static final String USER_NOT_FOUND_PASSWORD = "userNotFoundPassword";
//    private PasswordEncoder passwordEncoder;
//    private String userNotFoundEncodedPassword;
//    private SaltSource saltSource;
//    private UserDetailsService userDetailsService;
//    private SessionRegistry sessionRegistry;
//
//    public EhrWebAuthenticationProvider() {
//        this.setPasswordEncoder((PasswordEncoder)(new PlaintextPasswordEncoder()));
//    }
//
//    public EhrWebAuthenticationProvider(UserDetailsService userDetailsService) {
//        this.userDetailsService = userDetailsService;
//        this.setPasswordEncoder((PasswordEncoder)(new PlaintextPasswordEncoder()));
//    }
//
//    /**
//    public EhrWebAuthenticationProvider(UserDetailsService userDetailsService, SessionRegistry sessionRegistry) {
//        this.userDetailsService = userDetailsService;
//        this.sessionRegistry = sessionRegistry;
//        this.setPasswordEncoder((PasswordEncoder)(new PlaintextPasswordEncoder()));
//    }
//     */
//
//    /**
//     * Step 3
//     * @param userDetails
//     * @param authentication
//     * @throws AuthenticationException
//     */
//    protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
//        Object salt = null;
//        if(this.saltSource != null) {
//            salt = this.saltSource.getSalt(userDetails);
//        }
//
//        if(authentication.getCredentials() == null) {
//            this.logger.debug("Authentication failed: no credentials provided");
//            throw new BadCredentialsException(this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
//        } else {
//            EhrWebAuthenticationToken ehrWebAuthenticationToken = (EhrWebAuthenticationToken) authentication;
//            if(!ehrWebAuthenticationToken.isSso()) {
//                String presentedPassword = authentication.getCredentials().toString();
//                if (!this.passwordEncoder.isPasswordValid(userDetails.getPassword(), presentedPassword, salt)) {
//                    this.logger.debug("Authentication failed: password does not match stored value");
//                    throw new BadCredentialsException(this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
//                }
//            }
//            //HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
//            //sessionRegistry.registerNewSession(request.getSession().getId(), userDetails);
//        }
//    }
//
//    protected void doAfterPropertiesSet() throws Exception {
//        Assert.notNull(this.userDetailsService, "A UserDetailsService must be set");
//    }
//
//    protected final UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
//        UserDetails loadedUser;
//        try {
//            loadedUser = this.getUserDetailsService().loadUserByUsername(username);
//        } catch (UsernameNotFoundException var6) {
//            if(authentication.getCredentials() != null) {
//                String presentedPassword = authentication.getCredentials().toString();
//                this.passwordEncoder.isPasswordValid(this.userNotFoundEncodedPassword, presentedPassword, (Object)null);
//            }
//
//            throw var6;
//        } catch (Exception var7) {
//            throw new InternalAuthenticationServiceException(var7.getMessage(), var7);
//        }
//
//        if(loadedUser == null) {
//            throw new InternalAuthenticationServiceException("UserDetailsService returned null, which is an interface contract violation");
//        } else {
//            return loadedUser;
//        }
//    }
//
//    public void setPasswordEncoder(Object passwordEncoder) {
//        Assert.notNull(passwordEncoder, "passwordEncoder cannot be null");
//        if(passwordEncoder instanceof PasswordEncoder) {
//            this.setPasswordEncoder((PasswordEncoder)passwordEncoder);
//        } else if(passwordEncoder instanceof org.springframework.security.crypto.password.PasswordEncoder) {
//            final org.springframework.security.crypto.password.PasswordEncoder delegate = (org.springframework.security.crypto.password.PasswordEncoder)passwordEncoder;
//            this.setPasswordEncoder(new PasswordEncoder() {
//                public String encodePassword(String rawPass, Object salt) {
//                    this.checkSalt(salt);
//                    return delegate.encode(rawPass);
//                }
//
//                public boolean isPasswordValid(String encPass, String rawPass, Object salt) {
//                    this.checkSalt(salt);
//                    return delegate.matches(rawPass, encPass);
//                }
//
//                private void checkSalt(Object salt) {
//                    Assert.isNull(salt, "Salt value must be null when used with crypto module PasswordEncoder");
//                }
//            });
//        } else {
//            throw new IllegalArgumentException("passwordEncoder must be a PasswordEncoder instance");
//        }
//    }
//
//    private void setPasswordEncoder(PasswordEncoder passwordEncoder) {
//        Assert.notNull(passwordEncoder, "passwordEncoder cannot be null");
//        this.userNotFoundEncodedPassword = passwordEncoder.encodePassword("userNotFoundPassword", (Object)null);
//        this.passwordEncoder = passwordEncoder;
//    }
//
//    protected PasswordEncoder getPasswordEncoder() {
//        return this.passwordEncoder;
//    }
//
//    public void setSaltSource(SaltSource saltSource) {
//        this.saltSource = saltSource;
//    }
//
//    protected SaltSource getSaltSource() {
//        return this.saltSource;
//    }
//
//    public void setUserDetailsService(UserDetailsService userDetailsService) {
//        this.userDetailsService = userDetailsService;
//    }
//
//    protected UserDetailsService getUserDetailsService() {
//        return this.userDetailsService;
//    }
//}

+ 65 - 65
app/app-iot-server/src/main/java/com/yihu/ehr/iot/security/core/EhrWebAuthenticationSuccessHandler.java

@ -1,65 +1,65 @@
package com.yihu.ehr.iot.security.core;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.ehr.agModel.user.UserDetailModel;
import com.yihu.ehr.iot.util.CurrentRequest;
import com.yihu.ehr.util.rest.Envelop;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * Created by progr1mmer on 2018/1/26.
 */
public class EhrWebAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    SessionRegistry sessionRegistry;
    /**
     * Step 4
     * @param httpServletRequest
     * @param httpServletResponse
     * @param authentication
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        Envelop envelop = new Envelop();
        envelop.setSuccessFlg(true);
        Map userMap = new HashMap();
        String id = (String) httpServletRequest.getAttribute("id");
        String username = (String) httpServletRequest.getAttribute("username");
        String realName = (String) httpServletRequest.getAttribute("realName");
        userMap.put("id", id);
        userMap.put("username", username);
        userMap.put("realName", realName);
        envelop.setObj(userMap);
        List modelList = new ArrayList<>();
        UserDetailModel userDetailModel = (UserDetailModel)httpServletRequest.getAttribute("user");
        modelList.add(userDetailModel);
        envelop.setDetailModelList(modelList);
        httpServletResponse.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        httpServletResponse.getWriter().print(objectMapper.writeValueAsString(envelop));
        sessionRegistry.registerNewSession(httpServletRequest.getSession().getId(),userDetailModel);
    }
}
//package com.yihu.ehr.iot.security.core;
//
//import com.fasterxml.jackson.databind.ObjectMapper;
//import com.yihu.ehr.agModel.user.UserDetailModel;
//import com.yihu.ehr.iot.util.CurrentRequest;
//import com.yihu.ehr.util.rest.Envelop;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.http.MediaType;
//import org.springframework.security.core.Authentication;
//import org.springframework.security.core.session.SessionRegistry;
//import org.springframework.security.core.userdetails.UserDetails;
//import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
//
//import javax.servlet.ServletException;
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
//import java.io.IOException;
//import java.util.ArrayList;
//import java.util.HashMap;
//import java.util.List;
//import java.util.Map;
//
///**
// * Created by progr1mmer on 2018/1/26.
// */
//public class EhrWebAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
//
//    @Autowired
//    private ObjectMapper objectMapper;
//
//    @Autowired
//    SessionRegistry sessionRegistry;
//
//    /**
//     * Step 4
//     * @param httpServletRequest
//     * @param httpServletResponse
//     * @param authentication
//     * @throws IOException
//     * @throws ServletException
//     */
//    @Override
//    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
//        Envelop envelop = new Envelop();
//        envelop.setSuccessFlg(true);
//        Map userMap = new HashMap();
//        String id = (String) httpServletRequest.getAttribute("id");
//        String username = (String) httpServletRequest.getAttribute("username");
//        String realName = (String) httpServletRequest.getAttribute("realName");
//        userMap.put("id", id);
//        userMap.put("username", username);
//        userMap.put("realName", realName);
//        envelop.setObj(userMap);
//
//        List modelList = new ArrayList<>();
//        UserDetailModel userDetailModel = (UserDetailModel)httpServletRequest.getAttribute("user");
//        modelList.add(userDetailModel);
//        envelop.setDetailModelList(modelList);
//
//        httpServletResponse.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
//        httpServletResponse.getWriter().print(objectMapper.writeValueAsString(envelop));
//
//        sessionRegistry.registerNewSession(httpServletRequest.getSession().getId(),userDetailModel);
//    }
//}

+ 54 - 54
app/app-iot-server/src/main/java/com/yihu/ehr/iot/security/core/EhrWebAuthenticationToken.java

@ -1,54 +1,54 @@
package com.yihu.ehr.iot.security.core;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.SpringSecurityCoreVersion;
import java.util.Collection;
/**
 * Sso integrated
 * Created by progr1mmer on 2018/1/27.
 */
public class EhrWebAuthenticationToken extends UsernamePasswordAuthenticationToken {
    private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;
    // ~ Instance fields
    // ================================================================================================
    private final Object principal;
    private Object credentials;
    private boolean isSso;
    // ~ Constructors
    // ===================================================================================================
    /**
     * This constructor can be safely used by any code that wishes to create a
     * <code>UsernamePasswordAuthenticationToken</code>, as the {@link #isAuthenticated()}
     * will return <code>false</code>.
     *
     */
        public EhrWebAuthenticationToken(Object principal, Object credentials, boolean isSso) {
        super(principal, credentials);
        this.principal = principal;
        this.credentials = credentials;
        this.isSso = isSso;
        setAuthenticated(false);
    }
    public boolean isSso() {
        return this.isSso;
    }
    @Override
    public Object getPrincipal() {
        return principal;
    }
    @Override
    public Object getCredentials() {
        return credentials;
    }
}
//package com.yihu.ehr.iot.security.core;
//
//import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
//import org.springframework.security.core.GrantedAuthority;
//import org.springframework.security.core.SpringSecurityCoreVersion;
//
//import java.util.Collection;
//
///**
// * Sso integrated
// * Created by progr1mmer on 2018/1/27.
// */
//public class EhrWebAuthenticationToken extends UsernamePasswordAuthenticationToken {
//
//    private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;
//
//    // ~ Instance fields
//    // ================================================================================================
//
//    private final Object principal;
//    private Object credentials;
//    private boolean isSso;
//
//    // ~ Constructors
//    // ===================================================================================================
//
//    /**
//     * This constructor can be safely used by any code that wishes to create a
//     * <code>UsernamePasswordAuthenticationToken</code>, as the {@link #isAuthenticated()}
//     * will return <code>false</code>.
//     *
//     */
//        public EhrWebAuthenticationToken(Object principal, Object credentials, boolean isSso) {
//        super(principal, credentials);
//        this.principal = principal;
//        this.credentials = credentials;
//        this.isSso = isSso;
//        setAuthenticated(false);
//    }
//
//    public boolean isSso() {
//        return this.isSso;
//    }
//
//    @Override
//    public Object getPrincipal() {
//        return principal;
//    }
//
//    @Override
//    public Object getCredentials() {
//        return credentials;
//    }
//}

+ 55 - 55
app/app-iot-server/src/main/java/com/yihu/ehr/iot/security/core/EhrWebContextLogoutHandler.java

@ -1,55 +1,55 @@
package com.yihu.ehr.iot.security.core;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.ehr.agModel.user.UserDetailModel;
import com.yihu.ehr.iot.util.CurrentRequest;
import com.yihu.ehr.util.rest.Envelop;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.util.Assert;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * Created by progr1mmer on 2018/1/26.
 */
public class EhrWebContextLogoutHandler extends SecurityContextLogoutHandler {
    protected final Log logger = LogFactory.getLog(this.getClass());
    @Autowired
    SessionRegistry sessionRegistry;
    /**
     * Step 5
     * @param httpServletRequest
     * @param httpServletResponse
     * @param authentication
     */
    @Override
    public void logout(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) {
        Assert.notNull(httpServletRequest, "HttpServletRequest required");
            HttpSession session = httpServletRequest.getSession(false);
            if (session != null) {
                this.logger.debug("removeSessionInformation, session: " + session.getId());
                sessionRegistry.removeSessionInformation(session.getId());
            }
    }
}
//package com.yihu.ehr.iot.security.core;
//
//import com.fasterxml.jackson.databind.ObjectMapper;
//import com.yihu.ehr.agModel.user.UserDetailModel;
//import com.yihu.ehr.iot.util.CurrentRequest;
//import com.yihu.ehr.util.rest.Envelop;
//import org.apache.commons.logging.Log;
//import org.apache.commons.logging.LogFactory;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.http.MediaType;
//import org.springframework.security.core.Authentication;
//import org.springframework.security.core.context.SecurityContext;
//import org.springframework.security.core.context.SecurityContextHolder;
//import org.springframework.security.core.session.SessionRegistry;
//import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
//import org.springframework.security.web.authentication.logout.LogoutHandler;
//import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
//import org.springframework.util.Assert;
//
//import javax.servlet.ServletException;
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
//import javax.servlet.http.HttpSession;
//import java.io.IOException;
//import java.util.ArrayList;
//import java.util.HashMap;
//import java.util.List;
//import java.util.Map;
//
///**
// * Created by progr1mmer on 2018/1/26.
// */
//public class EhrWebContextLogoutHandler extends SecurityContextLogoutHandler {
//
//    protected final Log logger = LogFactory.getLog(this.getClass());
//
//    @Autowired
//    SessionRegistry sessionRegistry;
//
//    /**
//     * Step 5
//     * @param httpServletRequest
//     * @param httpServletResponse
//     * @param authentication
//     */
//    @Override
//    public void logout(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) {
//        Assert.notNull(httpServletRequest, "HttpServletRequest required");
//            HttpSession session = httpServletRequest.getSession(false);
//            if (session != null) {
//                this.logger.debug("removeSessionInformation, session: " + session.getId());
//                sessionRegistry.removeSessionInformation(session.getId());
//            }
//    }
//}

+ 47 - 47
app/app-iot-server/src/main/java/com/yihu/ehr/iot/security/core/EhrWebUserDetails.java

@ -1,47 +1,47 @@
package com.yihu.ehr.iot.security.core;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.Collection;
/**
 * Created by progr1mmer on 2018/1/26.
 */
public class EhrWebUserDetails implements UserDetails {
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return null;
    }
    @Override
    public boolean isEnabled() {
        return false;
    }
    @Override
    public boolean isCredentialsNonExpired() {
        return false;
    }
    @Override
    public String getPassword() {
        return null;
    }
    @Override
    public String getUsername() {
        return null;
    }
    @Override
    public boolean isAccountNonExpired() {
        return false;
    }
    @Override
    public boolean isAccountNonLocked() {
        return false;
    }
}
//package com.yihu.ehr.iot.security.core;
//
//import org.springframework.security.core.GrantedAuthority;
//import org.springframework.security.core.userdetails.UserDetails;
//
//import java.util.Collection;
//
///**
// * Created by progr1mmer on 2018/1/26.
// */
//public class EhrWebUserDetails implements UserDetails {
//
//    @Override
//    public Collection<? extends GrantedAuthority> getAuthorities() {
//        return null;
//    }
//
//    @Override
//    public boolean isEnabled() {
//        return false;
//    }
//
//    @Override
//    public boolean isCredentialsNonExpired() {
//        return false;
//    }
//
//    @Override
//    public String getPassword() {
//        return null;
//    }
//
//    @Override
//    public String getUsername() {
//        return null;
//    }
//
//    @Override
//    public boolean isAccountNonExpired() {
//        return false;
//    }
//
//    @Override
//    public boolean isAccountNonLocked() {
//        return false;
//    }
//}

+ 85 - 87
app/app-iot-server/src/main/java/com/yihu/ehr/iot/security/core/EhrWebUserDetailsService.java

@ -1,87 +1,85 @@
package com.yihu.ehr.iot.security.core;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.ehr.agModel.user.UserDetailModel;
import com.yihu.ehr.iot.util.http.HttpHelper;
import com.yihu.ehr.iot.util.http.HttpResponse;
import com.yihu.ehr.util.rest.Envelop;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
//import org.springframework.session.FindByIndexNameSessionRepository;
import org.springframework.util.Assert;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
/**
 * Created by progr1mmer on 2018/1/26.
 */
public class EhrWebUserDetailsService implements UserDetailsService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    private final ObjectMapper objectMapper = new ObjectMapper();
    private final String profileInnerUrl;
    public EhrWebUserDetailsService(String profileInnerUrl){
        Assert.hasText(profileInnerUrl, "ProfileInnerUrl must not be empty or null");
        this.profileInnerUrl = profileInnerUrl;
    }
    /**
     * Step 2
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        try {
            Map<String, Object> params = new HashMap<>();
            params.put("login_code", username);
            HttpResponse httpResponse = HttpHelper.get(profileInnerUrl + "/users/" + username, params);
            if(httpResponse.getStatusCode() == 200) {
                Envelop envelop = this.objectMapper.readValue(httpResponse.getBody(), Envelop.class);
                if (envelop.isSuccessFlg()){
                    String user = this.objectMapper.writeValueAsString(envelop.getObj());
                    UserDetailModel userDetailModel = this.objectMapper.readValue(user, UserDetailModel.class);
                    String password = userDetailModel.getPassword();
                    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
                    //登陆成功后需要的属性
                    request.setAttribute("id", userDetailModel.getId());
                    request.setAttribute("username", username);
                    request.setAttribute("realName", userDetailModel.getRealName());
                    request.setAttribute("user",userDetailModel);
                    return new User(username, password, getGrantedAuthorities(username));
                }
                logger.error(httpResponse.getBody());
                logger.error(envelop.getErrorMsg());
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
        throw new UsernameNotFoundException(username);
    }
    private Collection<GrantedAuthority> getGrantedAuthorities(String username) {
        Collection<GrantedAuthority> authorities = new ArrayList<>(1);
        authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
        return authorities;
    }
}
//package com.yihu.ehr.iot.security.core;
//
//import com.fasterxml.jackson.databind.ObjectMapper;
//import com.yihu.ehr.agModel.user.UserDetailModel;
//import com.yihu.ehr.iot.util.http.HttpHelper;
//import com.yihu.ehr.iot.util.http.HttpResponse;
//import com.yihu.ehr.iot.yanshi.dao.UserDao;
//import com.yihu.ehr.util.rest.Envelop;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.security.core.GrantedAuthority;
//import org.springframework.security.core.authority.SimpleGrantedAuthority;
//import org.springframework.security.core.session.SessionRegistry;
//import org.springframework.security.core.userdetails.User;
//import org.springframework.security.core.userdetails.UserDetails;
//import org.springframework.security.core.userdetails.UserDetailsService;
//import org.springframework.security.core.userdetails.UsernameNotFoundException;
////import org.springframework.session.FindByIndexNameSessionRepository;
//import org.springframework.util.Assert;
//import org.springframework.web.context.request.RequestContextHolder;
//import org.springframework.web.context.request.ServletRequestAttributes;
//
//import javax.servlet.http.HttpServletRequest;
//import java.util.ArrayList;
//import java.util.Collection;
//import java.util.HashMap;
//import java.util.Map;
//
///**
// * Created by progr1mmer on 2018/1/26.
// */
//public class EhrWebUserDetailsService implements UserDetailsService {
//
//    private final Logger logger = LoggerFactory.getLogger(this.getClass());
//
//    private final ObjectMapper objectMapper = new ObjectMapper();
//
//    private final String profileInnerUrl;
//    private UserDao userDao;
//
//    public EhrWebUserDetailsService(String profileInnerUrl, UserDao userDao) {
//        Assert.hasText(profileInnerUrl, "ProfileInnerUrl must not be empty or null");
//        this.profileInnerUrl = profileInnerUrl;
//        this.userDao = userDao;
//    }
//
//    /**
//     * Step 2
//     *
//     * @param username
//     * @return
//     * @throws UsernameNotFoundException
//     */
//    @Override
//    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//        try {
//            Map<String, Object> params = new HashMap<>();
//            params.put("login_code", username);
//            com.yihu.ehr.iot.yanshi.model.User userObj = userDao.findByMobile(username);
//            if(userObj==null){
//                throw  new UsernameNotFoundException("用户不存在");
//            }
//            String password = userObj.getPassword();
//            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
//            //登陆成功后需要的属性
//            request.setAttribute("id", userObj.getCode());
//            request.setAttribute("username", userObj.getMobile());
//            request.setAttribute("realName", userObj.getName());
//            request.setAttribute("user", userObj);
//            return new User(username, password, getGrantedAuthorities(username));
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        throw new UsernameNotFoundException(username);
//    }
//
//    private Collection<GrantedAuthority> getGrantedAuthorities(String username) {
//        Collection<GrantedAuthority> authorities = new ArrayList<>(1);
//        authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
//        return authorities;
//    }
//
//}

+ 177 - 177
app/app-iot-server/src/main/java/com/yihu/ehr/iot/security/core/EhrWebUsernamePasswordAuthenticationFilter.java

@ -1,177 +1,177 @@
package com.yihu.ehr.iot.security.core;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.ehr.agModel.user.UserDetailModel;
import com.yihu.ehr.iot.util.http.HttpHelper;
import com.yihu.ehr.iot.util.http.HttpResponse;
import com.yihu.ehr.util.rest.Envelop;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.util.Assert;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
/**
 * Sso integrated
 * Created by progr1mmer on 2018/1/27.
 */
public class EhrWebUsernamePasswordAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
    private static Logger logger = LoggerFactory.getLogger(EhrWebUsernamePasswordAuthenticationFilter.class);
    public static final String SPRING_SECURITY_FORM_USERNAME_KEY = "username";
    public static final String SPRING_SECURITY_FORM_PASSWORD_KEY = "password";
    private ObjectMapper objectMapper = new ObjectMapper();
    private String usernameParameter = "username";
    private String passwordParameter = "password";
    private String clientIdParameter = "clientId";
    private String accessTokenParameter = "accessToken";
    private boolean postOnly = true;
    private final String oauth2InnerUrl;
    private final String profileInnerUrl;
    public EhrWebUsernamePasswordAuthenticationFilter(String oauth2InnerUrl, String profileInnerUrl) {
        super(new AntPathRequestMatcher("/login", "POST"));
        Assert.hasText(oauth2InnerUrl, "Oauth2InnerUrl must not be empty or null");
        Assert.hasText(profileInnerUrl, "ProfileInnerUrl must not be empty or null");
        this.oauth2InnerUrl = oauth2InnerUrl;
        this.profileInnerUrl = profileInnerUrl;
    }
    /**
     * Step 1
     * @param request
     * @param response
     * @return
     * @throws AuthenticationException
     */
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        if(this.postOnly && !request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        } else {
            String username = null;
            String password = null;
            if(isSso(request)) {
                Map<String, Object> params = new HashMap<>();
                params.put("clientId", this.obtainClientId(request));
                params.put("accessToken", this.obtainAccessToken(request));
                try {
                    HttpResponse httpResponse = HttpHelper.post(oauth2InnerUrl + "/oauth/validToken", params);
                    if(httpResponse.getStatusCode() == 200) {
                        Map<String, Object> map = objectMapper.readValue(httpResponse.getBody(), Map.class);
                        String loginName = (String) map.get("user");
                        //验证通过。赋值session中的用户信息
                        params.clear();
                        params.put("login_code", loginName);
                        httpResponse = HttpHelper.get(profileInnerUrl + "/users/" + loginName, params);
                        Envelop envelop = this.objectMapper.readValue(httpResponse.getBody(), Envelop.class);
                        String user = this.objectMapper.writeValueAsString(envelop.getObj());
                        UserDetailModel userDetailModel = this.objectMapper.readValue(user, UserDetailModel.class);
                        username = userDetailModel.getLoginCode();
                        password = userDetailModel.getPassword();
                    }else {
                        logger.error(httpResponse.getBody());
                    }
                }catch (Exception e) {
                    e.printStackTrace();
                }
            }else {
                username = this.obtainUsername(request);
                password = this.obtainPassword(request);
            }
            if(username == null) {
                username = "";
            }
            if(password == null) {
                password = "";
            }
            username = username.trim();
            UsernamePasswordAuthenticationToken authRequest = new EhrWebAuthenticationToken(username, password, isSso(request)); //单点登陆集成
            this.setDetails(request, authRequest);
            return this.getAuthenticationManager().authenticate(authRequest);
        }
    }
    //单点登陆集成 ------------ Start -------------
    protected String obtainClientId(HttpServletRequest request) {
        return request.getParameter(this.clientIdParameter);
    }
    protected String obtainAccessToken(HttpServletRequest request) {
        return request.getParameter(this.accessTokenParameter);
    }
    //单点登陆集成 ------------ End -------------
    protected String obtainPassword(HttpServletRequest request) {
        return request.getParameter(this.passwordParameter);
    }
    protected String obtainUsername(HttpServletRequest request) {
        return request.getParameter(this.usernameParameter);
    }
    public void setPostOnly(boolean postOnly) {
        this.postOnly = postOnly;
    }
    protected void setDetails(HttpServletRequest request, UsernamePasswordAuthenticationToken authRequest) {
        authRequest.setDetails(this.authenticationDetailsSource.buildDetails(request));
    }
    //单点登陆集成 ------------ Start -------------
    public void setClientIdParameter(String clientIdParameter) {
        Assert.hasText(clientIdParameter, "ClientId parameter must not be empty or null");
        this.clientIdParameter = clientIdParameter;
    }
    public void setAccessTokenParameter(String accessTokenParameter) {
        Assert.hasText(accessTokenParameter, "AccessTokenParameter parameter must not be empty or null");
        this.accessTokenParameter = accessTokenParameter;
    }
    //单点登陆集成 ------------ End -------------
    public void setUsernameParameter(String usernameParameter) {
        Assert.hasText(usernameParameter, "Username parameter must not be empty or null");
        this.usernameParameter = usernameParameter;
    }
    public void setPasswordParameter(String passwordParameter) {
        Assert.hasText(passwordParameter, "Password parameter must not be empty or null");
        this.passwordParameter = passwordParameter;
    }
    public final String getClientIdParameter() {
        return this.clientIdParameter;
    }
    public final String getAccessTokenParameter() {
        return this.accessTokenParameter;
    }
    public final String getUsernameParameter() {
        return this.usernameParameter;
    }
    public final String getPasswordParameter() {
        return this.passwordParameter;
    }
    private boolean isSso(HttpServletRequest request){
        return null != request.getParameter(accessTokenParameter);
    }
}
//package com.yihu.ehr.iot.security.core;
//
//import com.fasterxml.jackson.databind.ObjectMapper;
//import com.yihu.ehr.agModel.user.UserDetailModel;
//import com.yihu.ehr.iot.util.http.HttpHelper;
//import com.yihu.ehr.iot.util.http.HttpResponse;
//import com.yihu.ehr.util.rest.Envelop;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//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.web.authentication.AbstractAuthenticationProcessingFilter;
//import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
//import org.springframework.util.Assert;
//
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
//import java.util.HashMap;
//import java.util.Map;
//
///**
// * Sso integrated
// * Created by progr1mmer on 2018/1/27.
// */
//public class EhrWebUsernamePasswordAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
//
//    private static Logger logger = LoggerFactory.getLogger(EhrWebUsernamePasswordAuthenticationFilter.class);
//
//    public static final String SPRING_SECURITY_FORM_USERNAME_KEY = "username";
//    public static final String SPRING_SECURITY_FORM_PASSWORD_KEY = "password";
//    private ObjectMapper objectMapper = new ObjectMapper();
//    private String usernameParameter = "username";
//    private String passwordParameter = "password";
//    private String clientIdParameter = "clientId";
//    private String accessTokenParameter = "accessToken";
//    private boolean postOnly = true;
//
//    private final String oauth2InnerUrl;
//    private final String profileInnerUrl;
//
//    public EhrWebUsernamePasswordAuthenticationFilter(String oauth2InnerUrl, String profileInnerUrl) {
//        super(new AntPathRequestMatcher("/login", "POST"));
//        Assert.hasText(oauth2InnerUrl, "Oauth2InnerUrl must not be empty or null");
//        Assert.hasText(profileInnerUrl, "ProfileInnerUrl must not be empty or null");
//        this.oauth2InnerUrl = oauth2InnerUrl;
//        this.profileInnerUrl = profileInnerUrl;
//    }
//
//    /**
//     * Step 1
//     * @param request
//     * @param response
//     * @return
//     * @throws AuthenticationException
//     */
//    @Override
//    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
//        if(this.postOnly && !request.getMethod().equals("POST")) {
//            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
//        } else {
//            String username = null;
//            String password = null;
//            if(isSso(request)) {
//                Map<String, Object> params = new HashMap<>();
//                params.put("clientId", this.obtainClientId(request));
//                params.put("accessToken", this.obtainAccessToken(request));
//                try {
//                    HttpResponse httpResponse = HttpHelper.post(oauth2InnerUrl + "/oauth/validToken", params);
//                    if(httpResponse.getStatusCode() == 200) {
//                        Map<String, Object> map = objectMapper.readValue(httpResponse.getBody(), Map.class);
//                        String loginName = (String) map.get("user");
//                        //验证通过。赋值session中的用户信息
//                        params.clear();
//                        params.put("login_code", loginName);
//                        httpResponse = HttpHelper.get(profileInnerUrl + "/users/" + loginName, params);
//                        Envelop envelop = this.objectMapper.readValue(httpResponse.getBody(), Envelop.class);
//                        String user = this.objectMapper.writeValueAsString(envelop.getObj());
//                        UserDetailModel userDetailModel = this.objectMapper.readValue(user, UserDetailModel.class);
//                        username = userDetailModel.getLoginCode();
//                        password = userDetailModel.getPassword();
//                    }else {
//                        logger.error(httpResponse.getBody());
//                    }
//                }catch (Exception e) {
//                    e.printStackTrace();
//                }
//            }else {
//                username = this.obtainUsername(request);
//                password = this.obtainPassword(request);
//            }
//
//            if(username == null) {
//                username = "";
//            }
//            if(password == null) {
//                password = "";
//            }
//
//            username = username.trim();
//            UsernamePasswordAuthenticationToken authRequest = new EhrWebAuthenticationToken(username, password, isSso(request)); //单点登陆集成
//
//            this.setDetails(request, authRequest);
//            return this.getAuthenticationManager().authenticate(authRequest);
//        }
//    }
//
//    //单点登陆集成 ------------ Start -------------
//    protected String obtainClientId(HttpServletRequest request) {
//        return request.getParameter(this.clientIdParameter);
//    }
//
//    protected String obtainAccessToken(HttpServletRequest request) {
//        return request.getParameter(this.accessTokenParameter);
//    }
//    //单点登陆集成 ------------ End -------------
//
//    protected String obtainPassword(HttpServletRequest request) {
//        return request.getParameter(this.passwordParameter);
//    }
//
//    protected String obtainUsername(HttpServletRequest request) {
//        return request.getParameter(this.usernameParameter);
//    }
//
//    public void setPostOnly(boolean postOnly) {
//        this.postOnly = postOnly;
//    }
//
//    protected void setDetails(HttpServletRequest request, UsernamePasswordAuthenticationToken authRequest) {
//        authRequest.setDetails(this.authenticationDetailsSource.buildDetails(request));
//    }
//
//    //单点登陆集成 ------------ Start -------------
//    public void setClientIdParameter(String clientIdParameter) {
//        Assert.hasText(clientIdParameter, "ClientId parameter must not be empty or null");
//        this.clientIdParameter = clientIdParameter;
//    }
//
//    public void setAccessTokenParameter(String accessTokenParameter) {
//        Assert.hasText(accessTokenParameter, "AccessTokenParameter parameter must not be empty or null");
//        this.accessTokenParameter = accessTokenParameter;
//    }
//    //单点登陆集成 ------------ End -------------
//
//    public void setUsernameParameter(String usernameParameter) {
//        Assert.hasText(usernameParameter, "Username parameter must not be empty or null");
//        this.usernameParameter = usernameParameter;
//    }
//
//    public void setPasswordParameter(String passwordParameter) {
//        Assert.hasText(passwordParameter, "Password parameter must not be empty or null");
//        this.passwordParameter = passwordParameter;
//    }
//
//    public final String getClientIdParameter() {
//        return this.clientIdParameter;
//    }
//
//    public final String getAccessTokenParameter() {
//        return this.accessTokenParameter;
//    }
//
//    public final String getUsernameParameter() {
//        return this.usernameParameter;
//    }
//
//    public final String getPasswordParameter() {
//        return this.passwordParameter;
//    }
//
//    private boolean isSso(HttpServletRequest request){
//        return null != request.getParameter(accessTokenParameter);
//    }
//
//}

+ 36 - 36
app/app-iot-server/src/main/java/com/yihu/ehr/iot/security/entryPoint/LoginEntryPoint.java

@ -1,36 +1,36 @@
package com.yihu.ehr.iot.security.entryPoint;
import com.alibaba.fastjson.JSONObject;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
 * @author yeshijie on 2018/3/9.
 */
public class LoginEntryPoint extends LoginUrlAuthenticationEntryPoint {
    public LoginEntryPoint(String loginFormUrl) {
        super(loginFormUrl);
    }
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        JSONObject json = new JSONObject();
        json.put("status",998);
        json.put("errorMsg","未登录或,登录超时");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        response.getWriter().println(json.toString());
        response.getWriter().flush();
//        super.commence(request, response, authException);
    }
}
//package com.yihu.ehr.iot.security.entryPoint;
//
//import com.alibaba.fastjson.JSONObject;
//import org.springframework.security.core.AuthenticationException;
//import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;
//
//import javax.servlet.ServletException;
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
//import java.io.IOException;
//
///**
// * @author yeshijie on 2018/3/9.
// */
//public class LoginEntryPoint extends LoginUrlAuthenticationEntryPoint {
//
//
//    public LoginEntryPoint(String loginFormUrl) {
//        super(loginFormUrl);
//    }
//
//    @Override
//    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
//        JSONObject json = new JSONObject();
//        json.put("status",998);
//        json.put("errorMsg","未登录或,登录超时");
//        response.setCharacterEncoding("UTF-8");
//        response.setContentType("application/json");
//        response.getWriter().println(json.toString());
//        response.getWriter().flush();
//
////        super.commence(request, response, authException);
//    }
//
//
//}

+ 20 - 22
app/app-iot-server/src/main/java/com/yihu/ehr/iot/service/common/BaseService.java

@ -17,8 +17,6 @@ import com.yihu.ehr.util.rest.Envelop;
import org.apache.commons.lang.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.session.SessionInformation;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
@ -57,8 +55,8 @@ public class BaseService {
    protected String oauth2InnerUrl;
    @Value("${app.oauth2OuterUrl}")
    protected String oauth2OuterUrl;
    @Autowired
    protected SessionRegistry sessionRegistry;
//    @Autowired
//    protected SessionRegistry sessionRegistry;
    @Autowired
    protected HttpServletRequest request;
@ -66,29 +64,29 @@ public class BaseService {
     * 获取当前登录用户,当前已登录的用户都缓存在session中
     * @return
     */
    public JSONObject getCurrentUser(){
        JSONObject json = new JSONObject();
        String sessionId = request.getSession().getId();
        UserDetailModel user = null;
        SessionInformation sessionInformation = sessionRegistry.getSessionInformation(sessionId);
        if(null != sessionInformation.getPrincipal()){
            user = (UserDetailModel)sessionInformation.getPrincipal();
            json.put("id",user.getId());
            json.put("code",user.getLoginCode());
            json.put("name",user.getRealName());
        }
        return json;
    }
//    public JSONObject getCurrentUser(){
//        JSONObject json = new JSONObject();
//        String sessionId = request.getSession().getId();
//        UserDetailModel user = null;
//        SessionInformation sessionInformation = sessionRegistry.getSessionInformation(sessionId);
//        if(null != sessionInformation.getPrincipal()){
//            user = (UserDetailModel)sessionInformation.getPrincipal();
//            json.put("id",user.getId());
//            json.put("code",user.getLoginCode());
//            json.put("name",user.getRealName());
//        }
//        return json;
//    }
    /**
     * 获取登录信息
     * @return
     */
    public Map<String,Object> getLoginHeader(){
        Map<String, Object> header = new HashMap<>();
        header.put("User-Agent",getCurrentUser());
        return header;
    }
//    public Map<String,Object> getLoginHeader(){
//        Map<String, Object> header = new HashMap<>();
//        header.put("User-Agent",getCurrentUser());
//        return header;
//    }
    public String readFile(String filePath, String charSet) {

+ 64 - 72
app/app-iot-server/src/main/java/com/yihu/ehr/iot/service/common/LoginService.java

@ -4,7 +4,6 @@ import com.alibaba.fastjson.JSONObject;
import com.yihu.ehr.agModel.user.RoleOrgModel;
import com.yihu.ehr.agModel.user.UserDetailModel;
import com.yihu.ehr.constants.ServiceApi;
import com.yihu.ehr.constants.SessionAttributeKeys;
import com.yihu.ehr.iot.yanshi.dao.UserDao;
import com.yihu.ehr.iot.yanshi.model.User;
import com.yihu.ehr.model.geography.MGeographyDict;
@ -21,15 +20,8 @@ import com.yihu.ehr.util.log.LogService;
import com.yihu.ehr.util.rest.Envelop;
import com.yihu.jw.util.security.MD5;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
@ -205,70 +197,70 @@ public class LoginService extends BaseService {
        }
    }
    /**
     * 自动登录
     *
     * @param request
     * @param model
     * @param token
     * @return
     * @throws Exception
     */
    public Envelop autoLogin(HttpServletRequest request, Model model, @RequestParam String token) throws Exception {
        try {
            String clientId = request.getParameter("clientId").toString();
            Map<String, Object> params = new HashMap<>();
            params.put("clientId", clientId);
            params.put("accessToken", token);
            HttpResponse response = HttpHelper.post(oauth2InnerUrl + "/oauth/validToken", params);
            Map<String, Object> map = objectMapper.readValue(response.getBody(), Map.class);
            if ((Boolean) map.get("successFlg")) {
                AccessToken accessToken = objectMapper.readValue(objectMapper.writeValueAsString(map.get("data")), AccessToken.class);
                String loginName = accessToken.getUser();
                //验证通过。赋值session中的用户信息
                response = HttpHelper.get(profileInnerUrl + "/users/" + loginName, params);
                Envelop envelop = (Envelop) this.objectMapper.readValue(response.getBody(), Envelop.class);
                String ex = this.objectMapper.writeValueAsString(envelop.getObj());
                UserDetailModel userDetailModel = this.objectMapper.readValue(ex, UserDetailModel.class);
                //获取用户的角色,机构,视图 等权限
                getUserRolePermissions(userDetailModel, loginName, request);
                // 注:SessionAttributeKeys.CurrentUser 是用 @SessionAttributes 来最终赋值,换成用 session.setAttribute() 赋值后将会被覆盖。
                model.addAttribute(SessionAttributeKeys.CurrentUser, userDetailModel);
                HttpSession session = request.getSession();
                //增加超级管理员信息
                if (loginName.equals(permissionsInfo)) {
                    session.setAttribute(AuthorityKey.IsAccessAll, true);
                } else {
                    session.setAttribute(AuthorityKey.IsAccessAll, false);
                }
                session.setAttribute("isLogin", true);
                session.setAttribute("token", accessToken);
                session.setAttribute("loginName", loginName);
                session.setAttribute("userId", userDetailModel.getId());
                session.setAttribute("clientId", clientId);
                //获取用户角色信息
                List<Map<String, Object>> features = getUserFeatures(userDetailModel.getId());
                Collection<GrantedAuthority> grantedAuthorities = new ArrayList<>();
                if (features != null) {
                    for (Map<String, Object> temp : features) {
                        if (temp.get("url") != null && !StringUtils.isEmpty(temp.get("url").toString())) {
                            grantedAuthorities.add(new SimpleGrantedAuthority(temp.get("url").toString()));
                        }
                    }
                }
                //生成认证token
                Authentication AuthenticationToken = new UsernamePasswordAuthenticationToken(loginName, "", grantedAuthorities);
                //将信息存放到SecurityContext
                SecurityContextHolder.getContext().setAuthentication(AuthenticationToken);
                return success(userDetailModel);
            } else {
                String msg = String.valueOf(map.get("message"));
                return failed(msg);
            }
        } catch (Exception e) {
            return failed(e.getMessage());
        }
    }
//    /**
//     * 自动登录
//     *
//     * @param request
//     * @param model
//     * @param token
//     * @return
//     * @throws Exception
//     */
//    public Envelop autoLogin(HttpServletRequest request, Model model, @RequestParam String token) throws Exception {
//        try {
//            String clientId = request.getParameter("clientId").toString();
//            Map<String, Object> params = new HashMap<>();
//            params.put("clientId", clientId);
//            params.put("accessToken", token);
//            HttpResponse response = HttpHelper.post(oauth2InnerUrl + "/oauth/validToken", params);
//            Map<String, Object> map = objectMapper.readValue(response.getBody(), Map.class);
//            if ((Boolean) map.get("successFlg")) {
//                AccessToken accessToken = objectMapper.readValue(objectMapper.writeValueAsString(map.get("data")), AccessToken.class);
//                String loginName = accessToken.getUser();
//                //验证通过。赋值session中的用户信息
//                response = HttpHelper.get(profileInnerUrl + "/users/" + loginName, params);
//                Envelop envelop = (Envelop) this.objectMapper.readValue(response.getBody(), Envelop.class);
//                String ex = this.objectMapper.writeValueAsString(envelop.getObj());
//                UserDetailModel userDetailModel = this.objectMapper.readValue(ex, UserDetailModel.class);
//                //获取用户的角色,机构,视图 等权限
//                getUserRolePermissions(userDetailModel, loginName, request);
//                // 注:SessionAttributeKeys.CurrentUser 是用 @SessionAttributes 来最终赋值,换成用 session.setAttribute() 赋值后将会被覆盖。
//                model.addAttribute(SessionAttributeKeys.CurrentUser, userDetailModel);
//                HttpSession session = request.getSession();
//                //增加超级管理员信息
//                if (loginName.equals(permissionsInfo)) {
//                    session.setAttribute(AuthorityKey.IsAccessAll, true);
//                } else {
//                    session.setAttribute(AuthorityKey.IsAccessAll, false);
//                }
//                session.setAttribute("isLogin", true);
//                session.setAttribute("token", accessToken);
//                session.setAttribute("loginName", loginName);
//                session.setAttribute("userId", userDetailModel.getId());
//                session.setAttribute("clientId", clientId);
//                //获取用户角色信息
//                List<Map<String, Object>> features = getUserFeatures(userDetailModel.getId());
//                Collection<GrantedAuthority> grantedAuthorities = new ArrayList<>();
//                if (features != null) {
//                    for (Map<String, Object> temp : features) {
//                        if (temp.get("url") != null && !StringUtils.isEmpty(temp.get("url").toString())) {
//                            grantedAuthorities.add(new SimpleGrantedAuthority(temp.get("url").toString()));
//                        }
//                    }
//                }
//                //生成认证token
//                Authentication AuthenticationToken = new UsernamePasswordAuthenticationToken(loginName, "", grantedAuthorities);
//                //将信息存放到SecurityContext
//                SecurityContextHolder.getContext().setAuthentication(AuthenticationToken);
//                return success(userDetailModel);
//            } else {
//                String msg = String.valueOf(map.get("message"));
//                return failed(msg);
//            }
//        } catch (Exception e) {
//            return failed(e.getMessage());
//        }
//    }
    /**
     * 通过用户名密码获取token

+ 48 - 48
app/app-iot-server/src/main/java/com/yihu/ehr/iot/util/CurrentRequest.java

@ -1,48 +1,48 @@
package com.yihu.ehr.iot.util;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.ehr.agModel.user.UserDetailModel;
import com.yihu.ehr.iot.util.http.HttpHelper;
import com.yihu.ehr.iot.util.http.HttpResponse;
import com.yihu.ehr.iot.util.spring.SpringContextHolder;
import com.yihu.ehr.util.rest.Envelop;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.session.SessionInformation;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
 * @author lith
 * @created 2018/02/06
 */
@Component
public class CurrentRequest {
    @Autowired
    SessionRegistry sessionRegistry;
    /**
     * 获取当前登录用户,当前已登录的用户都缓存在session中
     * @param request
     * @return
     */
    public  UserDetailModel getCurrentUser(HttpServletRequest request){
        String sessionId = request.getSession().getId();
        UserDetailModel user = null;
        SessionInformation sessionInformation = sessionRegistry.getSessionInformation(sessionId);
        if(null != sessionInformation.getPrincipal()){
            user = (UserDetailModel)sessionInformation.getPrincipal();
        }
        return user;
    }
}
//package com.yihu.ehr.iot.util;
//
//import com.fasterxml.jackson.databind.ObjectMapper;
//import com.yihu.ehr.agModel.user.UserDetailModel;
//import com.yihu.ehr.iot.util.http.HttpHelper;
//import com.yihu.ehr.iot.util.http.HttpResponse;
//import com.yihu.ehr.iot.util.spring.SpringContextHolder;
//import com.yihu.ehr.util.rest.Envelop;
//import org.apache.commons.lang.StringUtils;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.context.annotation.Configuration;
//import org.springframework.security.core.session.SessionInformation;
//import org.springframework.security.core.session.SessionRegistry;
//import org.springframework.stereotype.Component;
//
//import javax.annotation.PostConstruct;
//import javax.servlet.http.HttpServletRequest;
//import java.io.IOException;
//import java.util.HashMap;
//import java.util.Map;
//import java.util.concurrent.ConcurrentHashMap;
//
///**
// * @author lith
// * @created 2018/02/06
// */
//@Component
//public class CurrentRequest {
//
//    @Autowired
//    SessionRegistry sessionRegistry;
//
//    /**
//     * 获取当前登录用户,当前已登录的用户都缓存在session中
//     * @param request
//     * @return
//     */
//    public  UserDetailModel getCurrentUser(HttpServletRequest request){
//        String sessionId = request.getSession().getId();
//        UserDetailModel user = null;
//        SessionInformation sessionInformation = sessionRegistry.getSessionInformation(sessionId);
//        if(null != sessionInformation.getPrincipal()){
//            user = (UserDetailModel)sessionInformation.getPrincipal();
//        }
//        return user;
//    }
//}