如何在iframe中实现Spring的预身份验证头?

时间:2016-08-02 05:55:51

标签: spring iframe pre-authentication

我是春天的新人。我开发了两个不同的应用程序app1和app2。 App1向App2发送标头请求(SM_USER)。使用SSO进行预身份验证的过程正常。但是,当我调用此App1在iframe中加载App2网址时,我们会在iframe中获取登录页面。我们的代码如下

App1代码-HTML

    <iframe width=100% height=600 frameborder="0" scrolling="yes" src=""
   id="output_iframe_id"> </iframe>
   </div>

<script language="javascript" type="text/javascript">
 $(document).ready(
   function() {        
    function pre-authtest() {    
     $.ajax({
      url : "linkget",
      type : "GET",
      success : function(response) {    
       $("#output_iframe_id").attr('src',
         response);     
      }
     });
    }
    pre-authtest();

</script>

App1代码 - 控制器

 @RequestMapping(value = "/linkget", method = RequestMethod.GET)
 @ResponseStatus(value = HttpStatus.OK)
 public URL sendPost(HttpSession session, ModelMap model) throws Exception {
  JSONObject jsonurl = new JSONObject();
  JSONArray jsonArrayurl = new JSONArray();

  Users user = (Users) session.getAttribute("user");
  String username = user.getUsername();
   List<Users> authkeyval1 = loginService.getauthkey(username);
   System.out.println("sample authkey"+authkeyval1.get(0).getAuthkey());
  String akey=authkeyval1.get(0).getAuthkey();
  System.out.println("authkeyyyy"+akey);
  URL url = new URL("http://localhost:7080/");
  HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
  httpCon.setDoOutput(true);
  httpCon.setRequestMethod("POST");
  httpCon.setRequestProperty("SM_USER", akey);
  httpCon.setRequestProperty("PASS", "123");
  OutputStreamWriter out = new OutputStreamWriter(
  httpCon.getOutputStream());
  jsonurl.put("url", httpCon);
  jsonArrayurl.add(jsonurl);
  InputStream is = httpCon.getInputStream();
  return httpCon.getURL();    
 }

我的SSO功能详情如下 App2代码

public class SSORequestHeaderAuthenticationFilter extends AbstractPreAuthenticatedProcessingFilter {

 @Autowired
 private bidservice Bidservice;

    private static final Logger log = LoggerFactory.getLogger(SSORequestHeaderAuthenticationFilter.class);
    private String principalRequestHeader = "SM_USER";
    /**
     * Configure a value in the applicationContext-security for local tests.
     */
    private String testUserId = "admin-admin";
    /**
     * Configure whether a missing SSO header is an exception.
     */
    private boolean exceptionIfHeaderMissing = false;

    /**
     * Read and return header named by <tt>principalRequestHeader</tt> from Request
     *
    * @throws PreAuthenticatedCredentialsNotFoundException if the header is missing and
     *                                                      <tt>exceptionIfHeaderMissing</tt> is set to <tt>true</tt>.
     */

    protected Object getPreAuthenticatedPrincipal(HttpServletRequest request) {


        String principal = request.getHeader(principalRequestHeader);

       System.out.println("获得认证信息===" + principal);


        if (principal == null) {
            if (exceptionIfHeaderMissing) {
                throw new PreAuthenticatedCredentialsNotFoundException(principalRequestHeader
                        + " header not found in request.");

           }
            if (request.getSession().getAttribute("session_user") != null) {
             System.out.println("session user"+request.getSession().getAttribute("session_user"));
               // A bit of a hack for testers - allow the principal to be
               // obtained by session. Must be set by a page with no security filters enabled.
               // should remove for production.

               principal = (String) request.getSession().getAttribute("session_user");
           }
            else if (StringUtils.isNotBlank(testUserId)) {
             System.out.println("spring configuration has a test user id " + testUserId);




                principal = testUserId;
            } 
        }
        // also set it into the session, sometimes that's easier for jsp/faces
        // to get at..
        request.getSession().setAttribute("session_user", principal);
       System.out.println("session user1"+request.getSession().getAttribute("session_user"));
        return principal;
    }

    /**
     * Credentials aren't applicable here for OAM WebGate SSO.
     */
    protected Object getPreAuthenticatedCredentials(HttpServletRequest request) {
        return "password_not_applicable";
    }

    public void setPrincipalRequestHeader(String principalRequestHeader) {
        Assert.hasText(principalRequestHeader, "principalRequestHeader must not be empty or null");
        this.principalRequestHeader = principalRequestHeader;
    }

    public void setTestUserId(String testId) {
        if (StringUtils.isNotBlank(testId)) {
            this.testUserId = testId;
        }
    }

    /**
     * Exception if the principal header is missing. Default <tt>false</tt>
    *
     * @param exceptionIfHeaderMissing
     */
    public void setExceptionIfHeaderMissing(boolean exceptionIfHeaderMissing) {
        this.exceptionIfHeaderMissing = exceptionIfHeaderMissing;
    }

}

App2代码 - 控制器

@CrossOrigin()
 @RequestMapping(value = "/", method = RequestMethod.POST)
 public String getHomePagepost(HttpSession session,ModelMap model) {  

  if(session.getAttribute("messages")!=null)
   session.removeAttribute("messages");
  Authentication auth = SecurityContextHolder.getContext()
    .getAuthentication();
  String uname = auth.getName();
  System.out.println("uname in /"+uname);

  List<Users> users = loginService.checkStatus(uname);
  /*BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
  System.out.println("Obtained pswd:"+users.get(0).getPassword());
  encoder.matches("456", users.get(0).getPassword());*/
  if (!users.isEmpty()) {
   Users userz = users.get(0);
   String Username = userz.getUsername();


   Integer Status = userz.getStatus();

   System.out.println("Here is "+Username);


   String displayname=userz.getDisplayname();
   session.setAttribute("NameofUser",displayname);



    String authority = authoritiesService.getUserAuthority(uname);

    if(authority.equals("ROLE_ADMIN")){


     return "redirect:/trafficsource";
    }
    else{

     return "redirect:/trafficsource";
    }


  } else {

   session.setAttribute("userInvalid", "Invalid username or password. Please try again!");
   return "redirect:/login";
  }
 }

请帮忙......

0 个答案:

没有答案