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.stereotype.Component;
27  import org.springframework.ui.Model;
28  import org.springframework.web.bind.annotation.RequestMapping;
29  import org.springframework.web.bind.annotation.RequestMethod;
30  import org.springframework.web.bind.annotation.RequestParam;
31  
32  /**
33   * Spring MVC controller responsible for authenticating the user.
34   *
35   * @since 0.1
36   */
37  @Component
38  @RequestMapping("/s/login")
39  public class LoginController {
40  
41      private static transient final Logger log = LoggerFactory.getLogger(LoginController.class);
42  
43      private static String loginView = "login";
44  
45      @RequestMapping(method = RequestMethod.GET)
46      protected String view() {
47          return loginView;
48      }
49  
50      @RequestMapping(method = RequestMethod.POST)
51      protected String onSubmit(@RequestParam("username") String username,
52                                @RequestParam("password") String password,
53                                Model model) throws Exception {
54  
55          UsernamePasswordTokenordToken.html#UsernamePasswordToken">UsernamePasswordToken token = new UsernamePasswordToken(username, password);
56  
57          try {
58              SecurityUtils.getSubject().login(token);
59          } catch (AuthenticationException e) {
60              log.debug("Error authenticating.", e);
61              model.addAttribute("errorInvalidLogin", "The username or password was not correct.");
62  
63              return loginView;
64          }
65  
66          return "redirect:/s/index";
67      }
68  }