2012년 11월 21일 수요일

spring security 사용상 주의점

Spring3에서 Security 사용

다음과 같을때 유용하다.
1. 관리자에게 권할 별로 접근 메뉴가 다르다(일반운영자, 최종관리자)
2. 동시접속로그인을 제한한다.

url별로 접근 제한을 할 수 있고 권한에 대해 인증을 할 수 있고 로그아웃, 로그인, 세션생성, 비밀번호체크등 많은 클래스파일 작업이 필요없다.


참조 : http://static.springsource.org/spring-security/site/docs/3.0.x/reference/springsecurity-single.html

1. web.xml 편집

1.1 contextConfigLocation 에 security.xml을 추가한다.
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /WEB-INF/applicationContext.xml
            classpath:security-context.xml
        </param-value>
    </context-param>


* 여기서 주의할 점은 servlet에서 적용한 contextConfigLocation에 사용하지 말아야 한다. 
이부분에 대해서는 http://actionscripter.tistory.com/28 를 참조 바란다.

    <servlet>
        <servlet-name>Servlet</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>
                classpath:web-context.xml
                classpath:security-context.xml<!-- 이곳에 이렇게 넣지 마세요 -->
            </param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>




1.2  springSecurityFilterChain 의 filter와 filter-mapping 을추가 

<filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>

<filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
</filter-mapping>

이로서 web.xml 수정되었다. 
이렇게 적용한후 실행을 하게되면 
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'springSecurityFilterChain' is defined 부분의 에러가 발생한다.

springSecurityFilterChain 을 정의해 주어야 한다는 내용인데 web.xml의 contextConfigLocation 에서 정의된 security-context.xml 파일을 수정하자


2. applicationContext-security.xml 편집
2.1 http 설정

<http auto-config='true'>
    <intercept-url pattern="/**" access="ROLE_USER" />
</http>

그릭 다시 실행을 하면  No bean named 'org.springframework.security.authenticationManager' is defined 이 발생한다.

2.2
<authentication-manager>
    <authentication-provider>
      <user-service>
        <user name="jimi" password="jimispassword" authorities="ROLE_USER, ROLE_ADMIN" />
        <user name="bob" password="bobspassword" authorities="ROLE_USER" />
      </user-service>
    </authentication-provider>
  </authentication-manager>

을 함께 넣어주면 실제적으로 로그인 페이지가 뜨는 것을 확인할 수 있다.
이때 로그인을 하기위해서는 authentication-provider 에서 정의된 user name 과 password 를 넣어주면 된다.



[security-context.xml] ################################################################################################
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
    xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:lang="http://www.springframework.org/schema/lang"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/security
        http://www.springframework.org/schema/security/spring-security-3.0.xsd
          http://www.springframework.org/schema/context
          http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <!-- ***************************************************************************** -->
    <!-- This context file exists for developers to enter in their own security configurations. -->
    <!-- ***************************************************************************** -->
    <http auto-config='true'>
        <intercept-url pattern="/**" access="ROLE_USER" />
    </http>
    
    <authentication-manager>
        <authentication-provider>
            <user-service>
                <user name="jimi" password="jimispassword" authorities="ROLE_USER, ROLE_ADMIN" />
                <user name="bob" password="bobspassword" authorities="ROLE_USER" />
            </user-service>
        </authentication-provider>
    </authentication-manager>
</beans:beans>

security xml sample

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
  xmlns:beans="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
           http://www.springframework.org/schema/security
           http://www.springframework.org/schema/security/spring-security-3.1.xsd">
    <debug/>      
    
 
          
    <beans:bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    <beans:property name="driverClassName" value="oracle.jdbc.OracleDriver" ></beans:property>
    <beans:property name="url" value="jdbc:oracle:thin:@localhost:1521:orcl" ></beans:property>
    <beans:property name="username" value="spring" ></beans:property>
    <beans:property name="password" value="cs550" ></beans:property>
 </beans:bean>
    <http pattern="/images/**"    security="none"/>
    <http pattern="/ckeditor/**"  security="none"/>
    <http pattern="/jquery/**"    security="none"/>
    <http pattern="/grid/**"      security="none"/>
 <http pattern="/css/**"       security="none"/>
 <http pattern="/resources/**" security="none"/>

 <http auto-config="true" use-expressions="true" >
    
        <intercept-url pattern="/login"  access="permitAll"/>
  <intercept-url pattern="/logout" access="permitAll"/>
  <intercept-url pattern="/denied" access="hasRole('ROLE_USER')"/>
  <intercept-url pattern="/**"     access="hasRole('ROLE_USER')"/>
  <intercept-url pattern="/user"   access="hasRole('ROLE_USER')"/>
  <intercept-url pattern="/admin"  access="hasRole('ROLE_ADMIN')"/>

  <form-login login-page="/login"
   authentication-failure-url="/login/failure"
   default-target-url="/"/>

  <access-denied-handler error-page="/denied"/>

  <logout invalidate-session="true"
   logout-success-url="/logout/success"
   logout-url="/logout"/>
      
    </http>
    <authentication-manager>
       <authentication-provider>
          <jdbc-user-service data-source-ref="dataSource"
               users-by-username-query="select username,password, enabled from users where username=?"
         authorities-by-username-query="select u.username, ur.authority from users u,authorities ur
              where u.username = ur.username and u.username =?"
          />
       </authentication-provider>
    </authentication-manager>     
  
</beans:beans>

2012년 4월 30일 월요일

ibatis procedure call

<parameterMap id="myParamMap" class="java.util.Map"> 
<parameter property="username" mode="IN" /> 
<parameter property="roles1" jdbcType="ORACLECURSOR" mode="OUT" /> 
<parameter property="roles2" jdbcType="ORACLECURSOR" mode="OUT" /> 
<parameter property="roles3" jdbcType="ORACLECURSOR" mode="OUT" /> 

</parameterMap

2012년 4월 26일 목요일

procedure SimpleJdbcCall


String procedureName = "procedure name";

this.procCall = new SimpleJdbcCall(jdbcTemplate)
                  .withProcedureName(procedureName)
                  .withoutProcedureColumnMetaDataAccess()
                  .useInParameterNames("year","buildId","ofSavings")
           
                  .declareParameters(
                new SqlParameter("",Types.VARCHAR),
                new SqlParameter("",Types.VARCHAR),
                new SqlParameter("",Types.VARCHAR),
                new SqlOutParameter("",Types.VARCHAR),
                new SqlOutParameter("",Types.VARCHAR));


Map in  = new HashMap<String,Object>();

in.put("parameter Id", parameterValue);
in.put("parameter Id", parameterValue);
in.put("parameter Id", parameterValue);
in.put("parameter Id",  parameterValue );
in.put("parameter Id",  parameterValue);
                 
Map out = procCall.execute(in);

return out;

jQuary Ajax Sample dataType 'json'


$.ajax({
    type: "POST",
    url: "<ContextRoot>/ajaxcall.dol",
    data: param,
    dataType: 'json',
    success: function(result){
     alert ("success");
      var count = result.data.length;

                   var sampleData = result.data[?].?????;
     
    },
    error: function() {
    alert("호출에 실패했습니다.");
    }
    });


@Controller
public Class SampleController {

    @Requestmapping (value="ajaxcall.do",method=RequestMethod.POST)

    public String  sampleHandle (){
      Map <String,Object> resultMap = new HashMap<String,Object>();
     
      // method Function Start
      // method Result Value
       
         resultMap.put ("data",Object);
      // method Function end


      String returnValue =  util.buildJson((HashMap) resultMap);
      return returnValue;
   }
}

2012년 3월 22일 목요일

SpringFramework 3.0 higher @ResponseBody Return Encoding Code UTF-8(한글문제) 해결방안

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.http.MediaType;
import org.springframework.http.converter.StringHttpMessageConverter;

public class UTF8StringBeanPostProcessor implements BeanPostProcessor {

    public Object postProcessAfterInitialization(Object bean, String beanName)
            throws BeansException {
       
        if(bean instanceof StringHttpMessageConverter){ 
            MediaType mediaType = new MediaType("text", "plain", Charset.forName("UTF-8")); 
            List<MediaType> types = new ArrayList<MediaType>(); 
            types.add(mediaType); 
            ((StringHttpMessageConverter) bean).setSupportedMediaTypes(types); 
        } 
       
        return bean;
    }

    public Object postProcessBeforeInitialization(Object bean, String beanName)
            throws BeansException {
        return bean;
    }

}









SpringContext.xml



 <bean
      class="com.weems.common.append.config.UTF8StringBeanPostProcessor"></bean>


web.xml

 <filter>
    <filter-name>encodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>UTF-8</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>





Example :


@Controller
@RequestMapping ("home")

public class HomeController {

       @RequuestMapping (value="/response.do",method=RequestMethod.GET)
       public @ResponseBody String responseHandle (){
             String returnString = "한글 땡땡땡 or UTF-8 Code ";
             return returnString;
       }
     
}



or  ResponseEntity Use

   HttpHeaders responseHeaders = new HttpHeaders();
   responseHeaders.setContentType(MediaType.APPLICATION_JSON);

   String returnString = "한글 땡땡땡 or UTF-8 Code ";
   return new   ResponseEntity<Domain>
          (returnString,responseHeaders,HttpStatus.CREATED);



2012년 2월 21일 화요일

Failed to convert property value of type org.springframework.web.multipart.commons.CommonsMultipartFile to required type java.lang.String for property attach

Spring Error Messages : Failed to convert property value of type org.springframework.web.multipart.commons.CommonsMultipartFile to required type java.lang.String for property attach;
nested exception is java.lang.IllegalStateException: Cannot convert value of type [org.springframework.web.multipart.commons.CommonsMultipartFile] to required type [java.lang.String] for property attach: no matching editors or conversion strategy found;

 Spring FileUpload Method convert property value of type missmatch

Domain.java

public class Domain {
     String name; 
     String file;    // => to  CommonsMultipartFile file;

    ..  getter  and setter ..
}

Controller.java
public class uploadController {

               public String uploadHandle(@RequestParam ("file") MultipartFile file ){
                       // more method Control;
               }
}

upload.jsp

<form  method="post" action="upload.do" commandName="domain" 
                                 enctype="multipart/form-data >
<input  type="text" id="name" name="name" />
<input  type="file" id="file" name="file" />
<input type="sumit" value="transfer"  />
</form>