View Javadoc

1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *     http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.apache.shiro.samples.spring.web;
20  
21  import org.apache.shiro.SecurityUtils;
22  import org.apache.shiro.authc.AuthenticationException;
23  import org.apache.shiro.authc.UsernamePasswordToken;
24  import org.slf4j.Logger;
25  import org.slf4j.LoggerFactory;
26  import org.springframework.validation.BindException;
27  import org.springframework.web.servlet.ModelAndView;
28  import org.springframework.web.servlet.mvc.SimpleFormController;
29  
30  import javax.servlet.http.HttpServletRequest;
31  import javax.servlet.http.HttpServletResponse;
32  
33  /**
34   * Spring MVC controller responsible for authenticating the user.
35   *
36   * @since 0.1
37   */
38  public class LoginController extends SimpleFormController {
39  
40      private static transient final Logger log = LoggerFactory.getLogger(LoginController.class);
41  
42      protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object cmd, BindException errors) throws Exception {
43  
44          LoginCommand command = (LoginCommand) cmd;
45  
46          UsernamePasswordToken token = new UsernamePasswordToken(command.getUsername(), command.getPassword());
47  
48          try {
49              SecurityUtils.getSubject().login(token);
50          } catch (AuthenticationException e) {
51              log.debug("Error authenticating.", e);
52              errors.reject("error.invalidLogin", "The username or password was not correct.");
53          }
54  
55          if (errors.hasErrors()) {
56              return showForm(request, response, errors);
57          } else {
58              return new ModelAndView(getSuccessView());
59          }
60      }
61  }