2016-09-02 4 views
-1

기본 URL http://localhost:8180/MyProject/을 사용하여 응용 프로그램 또는 액세스를 시작하면 로그인 페이지를 전달하고 실제 홈 페이지를 표시하고 사용자를 익명으로 보지만 로그인 페이지를 먼저로드해야합니다. 유효성을 확인한 후 홈 페이지를 표시해야합니다. 제안을 부탁드립니다!로그인 문제 봄 보안

****의 SecurityConfig ****

import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.context.annotation.Bean; 
import org.springframework.context.annotation.Configuration; 
import org.springframework.security.authentication.AuthenticationProvider; 
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.configuration.EnableWebSecurity; 
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; 
import org.springframework.security.ldap.authentication.ad.ActiveDirectoryLdapAuthenticationProvider; 

@Configuration 
@EnableWebSecurity 
public class SecurityConfiguration extends WebSecurityConfigurerAdapter { 

    @Autowired 
    protected void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { 

     auth.authenticationProvider(activeDirectoryLdapAuthenticationProvider()); 
    } 

    @Override 
    protected void configure(HttpSecurity http) throws Exception { 
     http.authorizeRequests() 
     .antMatchers("/", "/home").permitAll() 
     .antMatchers("/admin/**").access("hasRole('ADMIN')") 
     .and().formLogin().loginPage("/login") 
     .usernameParameter("ssoId").passwordParameter("password") 
     .and().csrf() 
     .and().exceptionHandling().accessDeniedPage("/Access_Denied"); 
    } 

    @Bean 
    public AuthenticationProvider activeDirectoryLdapAuthenticationProvider() { 
     ActiveDirectoryLdapAuthenticationProvider authenticationProvider = 
      new ActiveDirectoryLdapAuthenticationProvider("", ""); 

     authenticationProvider.setConvertSubErrorCodesToExceptions(true); 
     authenticationProvider.setUseAuthenticationRequestCredentials(true); 

     return authenticationProvider; 
    }  
} 

당신은 당신이 처음으로 인증을 원하는 경우 .isAuthenticated()에 봄 권한 표현 .permitAll()을 변경해야

import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 

import org.springframework.security.core.Authentication; 
import org.springframework.security.core.context.SecurityContextHolder; 
import org.springframework.security.core.userdetails.UserDetails; 
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler; 
import org.springframework.stereotype.Controller; 
import org.springframework.ui.ModelMap; 
import org.springframework.web.bind.annotation.RequestMapping; 
import org.springframework.web.bind.annotation.RequestMethod; 
import org.springframework.web.bind.annotation.RequestParam; 
import org.springframework.web.bind.annotation.ResponseBody; 




@Controller 
public class MyController{ 


    @RequestMapping(value="/processAccount", method = RequestMethod.POST) 
    public @ResponseBody String processRequestAccount(ModelMap model,@RequestParam("accountNumber") String accountNumber,@RequestParam("companyNumber") String companyNumber) { 
     //String accountNumber = request.getParameter("accountNumber"); 

     String responseMessage = null; 
      //String companyNumber = request.getParameter("companyNumber"); 
      System.out.println(companyNumber); 
      MyServiceImpl accService = new MyServiceImpl(); 
      boolean responseFlag = accService.verifyAndProcessAccount(accountNumber, companyNumber); 
      System.out.println(responseFlag); 

      if(responseFlag) 
      { 
       //model.addAttribute("message", "The account number"+" "+accountNumber+" "+"is processed successfully!"); 

       responseMessage = "The account number"+" "+accountNumber+" "+"is processed successfully!"; 
      } 
      else 
      { 

      responseMessage = "Account number"+" "+accountNumber+" "+"cannot not be found, email has sent to the support team"; 

      } 



     return responseMessage; 

    } 


    @RequestMapping(value = { "/", "/home" }, method = RequestMethod.GET) 
    public String homePage(ModelMap model) { 
     model.addAttribute("user", getPrincipal()); 
     model.addAttribute("companyNumber","1"); 
     return "accountsearch"; 
    } 

    @RequestMapping(value = "/admin", method = RequestMethod.GET) 
    public String adminPage(ModelMap model) { 
     model.addAttribute("user", getPrincipal()); 
     return "admin"; 
    } 

    @RequestMapping(value = "/db", method = RequestMethod.GET) 
    public String dbaPage(ModelMap model) { 
     model.addAttribute("user", getPrincipal()); 
     return "dba"; 
    } 

    @RequestMapping(value = "/Access_Denied", method = RequestMethod.GET) 
    public String accessDeniedPage(ModelMap model) { 
     model.addAttribute("user", getPrincipal()); 
     return "accessDenied"; 
    } 

    @RequestMapping(value = "/login", method = RequestMethod.GET) 
    public String loginPage() { 
     return "login"; 
    } 

    @RequestMapping(value="/logout", method = RequestMethod.GET) 
    public String logoutPage (HttpServletRequest request, HttpServletResponse response) { 
     Authentication auth = SecurityContextHolder.getContext().getAuthentication(); 
     if (auth != null){  
      new SecurityContextLogoutHandler().logout(request, response, auth); 
     } 
     return "redirect:/login?logout"; 
    } 

    private String getPrincipal(){ 
     String userName = null; 
     Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); 

     if (principal instanceof UserDetails) { 
      userName = ((UserDetails)principal).getUsername(); 
     } else { 
      userName = principal.toString(); 
     } 
     return userName; 
    } 



} 
+0

나는 보안과 봄에 나는 온라인으로 몇 가지 예를 다음 되었더라도 요청을 리디렉션하는 방법에 대해 확신하지 봄에 실제로 새로운 오전보십시오. 내 개미작에 이상이 있니? – sam

+0

그것은 그 페이지에 모든 사용자를 허용한다는 것을 의미합니다. 그러나 LDAP ActiveDirectoryLdapAuthenticationProvider를 사용하는 대신 사용자 이름과 암호를 하드 코드하면 로그인 페이지를로드 할 수 있지만 AD를 추가하면 익명 사용자가 허용됩니다. – sam

+0

나는 그것을 추측하고 있습니다. 컨트롤러 클래스와 관련이 있습니까? 위의 컨트롤러 클래스를 붙여 넣었습니다. 내가 지시하지 않는다면 리디렉션에 대해 확신하지 못합니까? 비록 리디렉션을 변경하려고해도 CSS도 디스플레이에 적용됩니다. – sam

답변

0

MyController에.

는이

http.authorizeRequests() 
    .antMatchers("/login").isAnonymous() // anonymous user access this page 
    .antMatchers("/", "/home").isAuthenticated() // now home will be check authentication first 
    .antMatchers("/admin/**").access("hasRole('ADMIN')") 
    .and().formLogin().loginPage("/login") 
    .usernameParameter("ssoId").passwordParameter("password") 
    .and().csrf() 
    .and().exceptionHandling().accessDeniedPage("/Access_Denied");